﻿using AutoMapper;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SqlSugar;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;
using NetTaste;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Logging;
using System.Linq.Expressions;
using NPOI.SS.Formula.Functions;
using DFGK_WMS.Model.Enum;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using static NPOI.HSSF.Util.HSSFColor;
using Newtonsoft.Json;
using DFGK.WMS.Common;
using NPOI.POIFS.Crypt.Dsig;
using System.Text.RegularExpressions;
using DFGK.WMS.Common.Web;
using System.Net;

namespace DFGK_WMS.Repository
{
    /// <summary>
    /// 出库管理
    /// </summary>
    public class TShippingOrderDetailRepository : BaseRepository<TShippingOrderDetail>, ITShippingOrderDetailRepository
    {
        private readonly IMapper mapper;
        private readonly ITShippingLockCellRepository lockCellRepository;
        //public ITReceivingBillRepository TreceService { get; }

        public ITCellRepository cellRepository;
        IBarCodeRuleRepository barCodeRuleRepository { get; set; }
        public TShippingOrderDetailRepository(
            DFGK_DB context,
            IMapper mapper,
            ITShippingLockCellRepository lockCellRepository,
            /*, ITReceivingBillRepository treceService,*/
            ITCellRepository tCellRepository,
            IBarCodeRuleRepository barCodeRuleRepository
            ) : base(context, mapper)
        {
            this.mapper = mapper;
            this.lockCellRepository = lockCellRepository;
            //TreceService = treceService;
            this.cellRepository = tCellRepository;
            this.barCodeRuleRepository = barCodeRuleRepository;
        }

        /// <summary>
        /// 添加出库管理
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool AddTShippingOrderDetail(TShippingOrderDetail model)
        {
            using (var tran = Context.Database.BeginTransaction())
            {
                try
                {
                    //订单号
                    //单据类型
                    //合同号
                    //物料分类 优先级为顶级 默认为0
                    //物料名称
                    var material = Context.TMaterials.Find(model.MaterialId);
                    if (material != null)
                    {
                        model.MaterialCode = material.Code;
                        model.MaterialName = material.Name;
                        model.MaterialTypeCode = material.TypeCode;
                        model.UnitId = material.UnitId;
                        model.UnitName = material.UnitName;
                    }

                    //物料批次信息
                    // 根据 MaterialId 和 MaterialName 查询对应的物料批次记录
                    var materialkey = Context.TMaterialKeys.FirstOrDefault(m =>
                        m.MaterialId == model.MaterialId && m.MaterialName == model.MaterialName);
                    if (materialkey != null)
                    {
                        model.BatchNo = materialkey.BatchNo;
                    }

                    //库房信息
                    var house = Context.TWarehouses.Find(model.WarehouseId);
                    if (house != null)
                    {
                        model.WarehouseCode = house.Code;
                        model.WarehouseName = house.Name;

                        // 根据 AreaName 和 WarehouseId 查询对应的库区记录
                        var area = Context.TAreas.FirstOrDefault(m =>
                            m.Name == model.AreaName && m.WhId == model.WarehouseId);
                        if (area != null)
                        {
                            model.AreaCode = area.Code;
                        }
                    }

                    //出库站台
                    var station = Context.TStations.Find(model.StationId);
                    if (station != null)
                    {
                        model.StationName = station.Name;
                    }

                    //出库数默认为0
                    model.PickedQty = model.Qty;
                    model.ShippedQty = 0;
                    model.Status = 0;
                    //部门
                    var userobj = Context.TUsers.Find(model.NowUserId);
                    if (userobj != null)
                    {
                        var deptobj = Context.TDepartments.Find(userobj.DepartmentId);
                        if (deptobj != null)
                        {
                            model.DeptName = deptobj.DepartmentName;
                            model.DeptCode = deptobj.DepartmentCode;
                        }
                    }

                    #region 审计字段

                    model.CreateUserId = model.NowUserId;
                    model.CreateUserName = model.NowUserRealName;
                    model.CreateDate = DateTime.Now;
                    model.ModifyUserId = model.NowUserId;
                    model.ModifyUserName = model.NowUserRealName;
                    model.ModifyDate = DateTime.Now;
                    model.AuditUserId = model.NowUserId;
                    model.AuditUserName = model.NowUserRealName;
                    model.AuditDate = DateTime.Now;
                    model.SubmitUserId = model.NowUserId;
                    model.SubmitUserName = model.NowUserRealName;
                    model.SubmitDate = DateTime.Now;

                    #endregion 审计字段

                    //供应商
                    var supper = Context.TSuppliers.Find(model.SupplierId);
                    if (supper != null)
                    {
                        model.SupplierName = supper.Name;
                    }

                    //货主
                    var owner = Context.TOwners.Find(model.OwnerId);
                    if (owner != null)
                    {
                        model.OwnerName = owner.Name;
                    }

                    Context.TShippingOrderDetails.Add(model);
                    Context.SaveChanges();



                    //货位锁定明细
                    foreach (var item in model.LockCell)
                    {
                        var inv = Context.TInventories.Where(s => s.Id == item.InventoryId).FirstOrDefault();
                        inv.Status = 4;
                        //item.AvailableQty = item.AvailableQty - item.OutQty;
                        Context.TInventories.Update(inv);
                        //货位锁定明细
                        TShippingLockCell m = new TShippingLockCell();
                        m.OrderDetailId = model.Id;
                        m.InventoryId = item.InventoryId;
                        m.CellId = item.CellId;
                        m.CellCode = item.CellCode;
                        m.CellName = item.CellName;
                        m.PalletBarcode = item.PalletBarcode;
                        m.WhId = model.WarehouseId;
                        m.CellDepthIndex = 0;
                        //组垛Id不知道
                        m.StackingStorageId = 0;
                        m.OutQty = item.OutQty;
                        m.InventoryQty = item.InventoryQty;
                        m.MaterialId = item.MaterialId;
                        m.MaterialName = item.MaterialName;
                        m.MaterialCode = item.MaterialCode;
                        m.MaterialKeyId = item.MaterialKeyId;
                        m.BatchNo = item.BatchNo;
                        m.CreateDate = DateTime.Now;
                        m.RoutewayId = item.RoutewayId;
                        Context.TShippingLockCells.Add(m);

                        // 添加货品表
                        TShippingGoodsDetail product = new TShippingGoodsDetail();
                        product.OrderDetailId = model.Id;
                        product.MaterialId = item.MaterialId;
                        product.MaterialCode = item.MaterialCode;
                        product.MaterialName = item.MaterialName;
                        product.Status = 0;
                        product.PalletBarcode = item.PalletBarcode;
                        Context.TShippingGoodsDetails.Add(product);

                        Context.SaveChanges();
                    }

                    //无异常提交事务
                    tran.Commit();
                    return true;
                }
                catch (Exception)
                {
                    //事务回滚
                    tran.Rollback();
                    throw;
                }
            }
        }

        /// <summary>
        /// 添加出库管理 多个物料版本
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool AddTShippingOrderDetailPlus(TShippingOrderDetailPlusDTO model, out string msg)
        {
            msg = "添加出库单成功";
            using (var tran = Context.Database.BeginTransaction())
            {
                try
                {
                    //if (model.OrderSn.Length!=9)
                    //{
                    //    msg = "单号格式有误,必须为9位";
                    //    return false;
                    //}
                    var orderSnIsHove = Context.TShippingOrderDetails.Where(s => s.OrderSn == model.OrderSn);
                    if (orderSnIsHove != null && orderSnIsHove.Count() > 0)
                    {
                        msg = "单号已存在";
                        return false;
                    }
                    //if (string.IsNullOrEmpty(model.CarCode))
                    //{
                    //    msg = "车牌号不能为空";
                    //    return false;
                    //}
                    //var stationObj = Context.TStations.Find(model.StationId);
                    //if (stationObj == null)
                    //{
                    //    msg = "站台查询不到";
                    //    return false;
                    //}
                    //if (stationObj.Status == 0)
                    //{
                    //    msg = "站台已被禁用";
                    //    return false;
                    //}

                    foreach (var mater in model.ShippingOrderDetailPlusLockCellDTOs)
                    {

                        //客户
                        var cust = Context.TCustomers.Find(model.CustomerId);
                        if (cust == null)
                        {
                            tran.Rollback();
                            msg = "找不到客户";
                            return false;
                        }

                        //if (cust.MengNiuStatus == false)
                        //{
                        //    tran.Rollback();
                        //    msg = "客户已被禁用";
                        //    return false;
                        //}

                        //为了查询物料typeCode
                        var material = Context.TMaterials.FirstOrDefault(m => m.Code == mater.MaterialCode);
                        if (material == null)
                        {
                            tran.Rollback();
                            msg = "找不到此物料";
                            return false;
                        }

                        var invmter = Context.TInventories.Where(m => m.MaterialCode == mater.MaterialCode);
                        if (invmter == null || invmter.Count() <= 0)
                        {
                            tran.Rollback();
                            msg = "库存中没有此物料";
                            return false;
                        }

                        var lockCell = lockCellRepository.LockCell(mater.MaterialCode, mater.PallBarcode, mater.MaterialNum, out var lockCellList, out var errorMsg);
                        if (!lockCell)
                        {
                            tran.Rollback();
                            msg = errorMsg;
                            return false;
                        }

                        var shippingOrderDetail = new TShippingOrderDetail
                        {
                            OrderSn = model.OrderSn, //同一个订单号
                            CustomerId = cust.Id,
                            CustomerName = cust.Name,
                            MaterialId = material.Id,
                            MaterialName = mater.MaterialName,
                            MaterialTypeCode = material.TypeCode,
                            BillType = model.BillType,
                            WarehouseId = invmter.First().WarehouseId,
                            WarehouseCode = invmter.First().WarehouseCode,
                            WarehouseName = invmter.First().WarehouseName,
                            AreaCode = "",
                            AreaName = "",
                            BatchNo = "",
                            UnitName = material.UnitName,
                            Qty = mater.KeChuCount,
                            Status = 0,
                            CreateDate = DateTime.Now,
                            CreateUserName = model.NowUserRealName,
                            CreateUserId = model.NowUserId,
                            CarCord = model.CarCode,
                            StationId = 0,
                            StationName = "测试站台",
                            MaterialCode = mater.MaterialCode,
                            AGVStartPoint = model.AGVStartPoint,
                            AGVEndPoint = model.AGVEndPoint,
                        };
                        Context.TShippingOrderDetails.Add(shippingOrderDetail);
                        if (Context.SaveChanges() <= 0)
                        {
                            msg = "出库单添加失败,单号：" + model.OrderSn;
                            tran.Rollback();
                            return false;
                        }

                        //添加托盘满载率
                        var pallList = Context.TPallets.Where(x => x.PalletBarcode == invmter.First().PalletBarcode);
                        if (pallList.Count() == 0)
                        {
                            msg = "未查询到托盘";
                            tran.Rollback();
                            return false;
                        }
                        var pallListFirst = pallList.First();
                        pallListFirst.LoadFactor = mater.LoadFactor;
                        Context.TPallets.Update(pallListFirst);
                        if (Context.SaveChanges() <= 0)
                        {
                            msg = "更新托盘表满载率失败!";
                            tran.Rollback();
                            return false;
                        }


                        // 添加货品表
                        //var product = new TShippingGoodsDetail
                        //{
                        //    OrderDetailId = shippingOrderDetail.Id,
                        //    MaterialId = mater.MaterialId,
                        //    MaterialCode = mater.MaterialCode,
                        //    MaterialName = mater.MaterialName,
                        //    Status = 0
                        //};
                        //Context.TShippingGoodsDetails.Add(product);
                        //Context.SaveChanges();

                        //货位锁定明细
                        foreach (var item in lockCellList)
                        {
                            int i = 0;
                            var inv = Context.TInventories.Where(s => s.Id == item.InventoryId && s.PalletBarcode == mater.PallBarcode).FirstOrDefault();

                            if (inv == null && i == lockCellList.Count - 1)
                            {
                                msg = "暂无符合条件的库存信息";
                                tran.Rollback();
                                return false;
                            }
                            else if (inv == null)
                            {
                                continue;
                            }

                            inv.Status = 4;
                            Context.TInventories.Update(inv);
                            //货位锁定明细
                            var m = new TShippingLockCell
                            {
                                OrdeSn = model.OrderSn,
                                OrderDetailId = shippingOrderDetail.Id,
                                InventoryId = item.InventoryId,
                                CellId = item.CellId,
                                CellCode = item.CellCode,
                                CellName = item.CellName,
                                PalletBarcode = item.PalletBarcode,
                                WhId = item.WhId,
                                CellDepthIndex = 0,
                                StackingStorageId = item.StackingStorageId,
                                OutQty = mater.KeChuCount,
                                InventoryQty = mater.KeChuCount,
                                MaterialId = material.Id,
                                MaterialName = item.MaterialName,
                                MaterialCode = item.MaterialCode,
                                MaterialKeyId = item.MaterialKeyId,
                                BatchNo = item.BatchNo,
                                SmallBatchNo = item.SmallBatchNo,
                                CreateDate = DateTime.Now,
                                RoutewayId = item.RoutewayId,
                                IsPicking = false
                            };
                            Context.TShippingLockCells.Add(m);
                            if (Context.SaveChanges() <= 0)
                            {
                                msg = "出库单明细添加失败,物料：" + item.MaterialName + ",单号：" + model.OrderSn;
                                tran.Rollback();
                                return false;
                            }
                            i++;
                            #region
                            ////查询双深位的外层是否有货
                            var cellCode = inv.LocationCode;
                            var cellCodeNew = cellCode.Substring(3);
                            string message;
                            var cellCode1 = "";
                            var iscell = "";
                            string cellCodeNew2 = "";

                            if (cellCode.Substring(0, 1) == "A")
                            {
                                if (cellCode.Substring(2, 1) == "3")
                                {
                                    cellCodeNew2 = "A02" + cellCodeNew;
                                    var inventoryList = Context.TInventories.Where(x => x.LocationCode == cellCodeNew2).ToList();
                                    var cellList = Context.TCells.First(x => x.Code == cellCodeNew2);
                                    if (Context.TInventory.FirstOrDefault(x => x.LocationCode == cellCodeNew2) != null)
                                    {

                                        string modifiedcellcode = Regex.Replace(cellCode, "A03", "A02");
                                        string? cellcode = GetCellCode("1lou", out message);
                                        TCell? toCell = Context.TCells.AsNoTracking().FirstOrDefault(it => it.Code == cellcode);
                                        if (toCell == null)
                                        {
                                            message = "目标仓位不存在";
                                            return false;
                                        }
                                        else
                                        {
                                            toCell.FullStatus = 1;
                                            toCell.IsLock = false;
                                            toCell.BusinessType = 0;
                                            toCell.ModifyDate = DateTime.Now;
                                            toCell.Status = 1;
                                            Context.TCells.Update(toCell);
                                        }

                                        #region 修改库存状态
                                        var tinventorylist = Context.TInventory.Where(it => it.LocationCode == modifiedcellcode);
                                        if (!tinventorylist.Any())
                                        {
                                            message = "库存不存在";
                                            return false;
                                        }
                                        foreach (var inventory in tinventorylist)
                                        {
                                            inventory.LocationId = toCell.Id;
                                            inventory.LocationName = toCell.Name;
                                            inventory.LocationCode = toCell.Code;
                                            inventory.LocationDepth = toCell.DepthIndex;
                                            inventory.LocationLineNo = toCell.LineNo;
                                            inventory.LocationLayerNo = toCell.LayerNo;
                                            inventory.LocationColumnNo = toCell.ColumnNo;
                                            inventory.Status = 2;
                                            inventory.LocationHeightType = toCell.HeightType;
                                            inventory.IsLock = true;
                                            inventory.RoutewayId = toCell.RoutewayId;
                                            Context.Update(inventory);
                                            #region 关联的入库单做处理
                                            var revingobj = Context.TReceivingOrderDetails.Find(inventory.RelatedOrderDetailId);
                                            if (revingobj == null)
                                            {
                                                message = "入库单明细不存在或已被删除";
                                                return false;
                                            }
                                            else
                                            {
                                                revingobj.LocationId = toCell.Id;
                                                revingobj.LocationCode = toCell.Code;
                                                revingobj.LocationName = toCell.Name;
                                                revingobj.ModifyDate = DateTime.Now;
                                                Context.TReceivingOrderDetails.Update(revingobj);
                                            }
                                            //组垛信息
                                            var stackingobj = Context.TStackingStorages.FirstOrDefault(x => x.PalletBarcode == inventory.PalletBarcode && x.BatchNo == revingobj.BatchNo && x.MaterialId == revingobj.MaterialId && x.RelatedOrderDetailId == revingobj.Id);
                                            if (stackingobj == null)
                                            {
                                                message = "组垛信息不存在或已被删除";
                                                return false;
                                            }
                                            else
                                            {
                                                stackingobj.ExpectedLocation = toCell.Code;
                                                if (stackingobj.ActualLocation != null)
                                                {
                                                    stackingobj.ActualLocation = toCell.Code;
                                                }
                                                stackingobj.Status = 0;
                                                Context.TStackingStorages.Update(stackingobj);
                                            }
                                            int stackingid = stackingobj.Id;
                                            #region 指令管理
                                            TInstruct instruct = null;
                                            instruct = new TInstruct
                                            {
                                                WarehouseCode = "A2",
                                                Status = 4,
                                                FromLocation = "",
                                                ToLocation = toCell.Code,
                                                StackingStorageId = stackingobj.Id,
                                                WorkDeviceType = 1,
                                                InstructType = 3,
                                                Action = 0,
                                                RelatedOrderId = revingobj.Id,
                                                DeviceCode = "",
                                                ExpectedToLocation = toCell.Code,
                                                InstructIndex = 1,
                                                PalletBarcode = inventory.PalletBarcode,
                                                ScanedBarcode = inventory.PalletBarcode,
                                                Priority = 9999,
                                                Qty = inventory.AvailableQty == null ? 0 : (decimal)inventory.AvailableQty,
                                                FinishedQty = 0,
                                                StartTime = DateTime.Now,
                                                BusinessGroupId = Guid.NewGuid(),
                                                BusinessType = (int)EmBusinessType.Move,
                                                BillType = (int)revingobj.BillType.GetValueOrDefault(),
                                                LogicalCellAddr = revingobj.Erpcode
                                            };
                                            Context.TInstructs.Add(instruct);
                                            #endregion
                                        }
                                        #endregion


                                        #endregion
                                        #region 上架单
                                        string str = DateTime.Now.ToString("yyyyMMddHHmmss");// + 
                                        TPutawayOrder putawayOrder = new TPutawayOrder();
                                        putawayOrder.Code = str;
                                        putawayOrder.RelatedOrderDetailId = tinventorylist.First().RelatedOrderDetailId;
                                        putawayOrder.StackingStorageId = 0;
                                        putawayOrder.PalletBarcode = tinventorylist.First().PalletBarcode;
                                        putawayOrder.ParentPalletBarcode = tinventorylist.First().ParentPalletBarcode;
                                        putawayOrder.LocationCode = toCell.Code;
                                        putawayOrder.LocationDepth = toCell.DepthIndex == 0 ? null : toCell.DepthIndex;
                                        putawayOrder.Status = 5;
                                        putawayOrder.Qty = tinventorylist.First().AvailableQty;
                                        putawayOrder.CreateDate = DateTime.Now;
                                        putawayOrder.MaterialId = tinventorylist.First().MaterialId;
                                        putawayOrder.MaterialCode = tinventorylist.First().MaterialCode;
                                        putawayOrder.MaterialName = tinventorylist.First().MaterialName;
                                        putawayOrder.MaterialKeyId = tinventorylist.First().MaterialKeyId;
                                        putawayOrder.BatchNo = tinventorylist.First().BatchNo;
                                        putawayOrder.SmallBatchNo = "";
                                        putawayOrder.OwnerId = 0;
                                        putawayOrder.OwnerName = "";
                                        putawayOrder.CreateUserId = 0;
                                        putawayOrder.CreateUserName = "系统";
                                        putawayOrder.SourceType = 3;
                                        putawayOrder.SiteCode = "";
                                        Context.TPutawayOrders.Add(putawayOrder);
                                        var pallobj = Context.TPallets.FirstOrDefault(x => x.LocationCode == modifiedcellcode);
                                        if (pallobj != null)
                                        {
                                            pallobj.LocationName = toCell.Name;
                                            pallobj.LocationCode = toCell.Code;
                                        }

                                        #endregion
                                        #region 堆垛机                
                                        //堆垛机出库
                                        TaskLiku taskLiku = new TaskLiku()
                                        {
                                            taskId = str,
                                            taskSubType = "103",
                                            startPositionId = inv.LocationCode,
                                            endPositionId = toCell.Code,
                                            palletCode = mater.PallBarcode,
                                            type = 1

                                        };
                                        var taskLikudata = HttpHelper.WCSSendPostRequest("WMS/v1/CMD", taskLiku);
                                        //判断堆垛机返回的状态码不成功的话事务回滚

                                        //成功以后调用wms接口改库存状态

                                        #endregion

                                        //无异常提交事务
                                        msg = "";
                                        tran.Commit();
                                        return true;
                                    }
                                }

                            }
                            else if (cellCode.Substring(0, 1) == "B")
                            {
                                if (cellCode.Substring(2, 1) == "1")
                                {
                                    cellCodeNew2 = "B02" + cellCodeNew;
                                    var inventoryList = Context.TInventories.Where(x => x.LocationCode == cellCodeNew2).ToList();
                                    var cellList = Context.TCells.First(x => x.Code == cellCodeNew2);
                                    if (Context.TInventory.FirstOrDefault(x => x.LocationCode == cellCodeNew2) != null)
                                    {

                                        string? cellcode = GetCellCode("2lou", out message);
                                        TCell? toCell = Context.TCells.AsNoTracking().FirstOrDefault(it => it.Code == cellcode);
                                        if (toCell == null)
                                        {
                                            message = "目标仓位不存在";
                                            return false;
                                        }
                                        else
                                        {
                                            toCell.FullStatus = 1;
                                            toCell.IsLock = false;
                                            toCell.BusinessType = 0;
                                            toCell.ModifyDate = DateTime.Now;
                                            toCell.Status = 1;
                                            Context.TCells.Update(toCell);
                                        }

                                        #region 修改库存状态
                                        var tinventorylist = Context.TInventory.Where(it => it.LocationCode == cellCodeNew2);
                                        if (!tinventorylist.Any())
                                        {
                                            message = "库存不存在";
                                            return false;
                                        }
                                        foreach (var inventory in tinventorylist)
                                        {
                                            inventory.LocationId = toCell.Id;
                                            inventory.LocationName = toCell.Name;
                                            inventory.LocationCode = toCell.Code;
                                            inventory.LocationDepth = toCell.DepthIndex;
                                            inventory.LocationLineNo = toCell.LineNo;
                                            inventory.LocationLayerNo = toCell.LayerNo;
                                            inventory.LocationColumnNo = toCell.ColumnNo;
                                            inventory.Status = 2;
                                            inventory.LocationHeightType = toCell.HeightType;
                                            inventory.IsLock = true;
                                            inventory.RoutewayId = toCell.RoutewayId;
                                            Context.Update(inventory);
                                            #region 关联的入库单做处理
                                            var revingobj = Context.TReceivingOrderDetails.Find(inventory.RelatedOrderDetailId);
                                            if (revingobj == null)
                                            {
                                                message = "入库单明细不存在或已被删除";
                                                return false;
                                            }
                                            else
                                            {
                                                revingobj.LocationId = toCell.Id;
                                                revingobj.LocationCode = toCell.Code;
                                                revingobj.LocationName = toCell.Name;
                                                revingobj.ModifyDate = DateTime.Now;
                                                Context.TReceivingOrderDetails.Update(revingobj);
                                            }
                                            //组垛信息
                                            var stackingobj = Context.TStackingStorages.FirstOrDefault(x => x.PalletBarcode == inventory.PalletBarcode && x.BatchNo == revingobj.BatchNo && x.MaterialId == revingobj.MaterialId && x.RelatedOrderDetailId == revingobj.Id);
                                            if (stackingobj == null)
                                            {
                                                message = "组垛信息不存在或已被删除";
                                                return false;
                                            }
                                            else
                                            {
                                                stackingobj.ExpectedLocation = toCell.Code;
                                                if (stackingobj.ActualLocation != null)
                                                {
                                                    stackingobj.ActualLocation = toCell.Code;
                                                }
                                                stackingobj.Status = 0;
                                                Context.TStackingStorages.Update(stackingobj);
                                            }
                                            int stackingid = stackingobj.Id;
                                            #region 指令管理
                                            TInstruct instruct = null;
                                            instruct = new TInstruct
                                            {
                                                WarehouseCode = "A01",
                                                Status = 4,
                                                FromLocation = "",
                                                ToLocation = toCell.Code,
                                                StackingStorageId = stackingobj.Id,
                                                WorkDeviceType = 1,
                                                InstructType = 3,
                                                Action = 0,
                                                RelatedOrderId = revingobj.Id,
                                                DeviceCode = "",
                                                ExpectedToLocation = toCell.Code,
                                                InstructIndex = 1,
                                                PalletBarcode = inventory.PalletBarcode,
                                                ScanedBarcode = inventory.PalletBarcode,
                                                Priority = 9999,
                                                Qty = inventory.AvailableQty == null ? 0 : (decimal)inventory.AvailableQty,
                                                FinishedQty = 0,
                                                StartTime = DateTime.Now,
                                                BusinessGroupId = Guid.NewGuid(),
                                                BusinessType = (int)EmBusinessType.Move,
                                                BillType = (int)revingobj.BillType.GetValueOrDefault(),
                                                LogicalCellAddr = revingobj.Erpcode
                                            };
                                            Context.TInstructs.Add(instruct);
                                            #endregion
                                        }
                                        #endregion


                                        #endregion
                                        #region 上架单
                                        string str = DateTime.Now.ToString("yyyyMMddHHmmss");// + 
                                        TPutawayOrder putawayOrder = new TPutawayOrder();
                                        putawayOrder.Code = str;
                                        putawayOrder.RelatedOrderDetailId = tinventorylist.First().RelatedOrderDetailId;
                                        putawayOrder.StackingStorageId = 0;
                                        putawayOrder.PalletBarcode = tinventorylist.First().PalletBarcode;
                                        putawayOrder.ParentPalletBarcode = tinventorylist.First().ParentPalletBarcode;
                                        putawayOrder.LocationCode = toCell.Code;
                                        putawayOrder.LocationDepth = toCell.DepthIndex == 0 ? null : toCell.DepthIndex;
                                        putawayOrder.Status = 5;
                                        putawayOrder.Qty = tinventorylist.First().AvailableQty;
                                        putawayOrder.CreateDate = DateTime.Now;
                                        putawayOrder.MaterialId = tinventorylist.First().MaterialId;
                                        putawayOrder.MaterialCode = tinventorylist.First().MaterialCode;
                                        putawayOrder.MaterialName = tinventorylist.First().MaterialName;
                                        putawayOrder.MaterialKeyId = tinventorylist.First().MaterialKeyId;
                                        putawayOrder.BatchNo = tinventorylist.First().BatchNo;
                                        putawayOrder.SmallBatchNo = "";
                                        putawayOrder.OwnerId = 0;
                                        putawayOrder.OwnerName = "";
                                        putawayOrder.CreateUserId = 0;
                                        putawayOrder.CreateUserName = "系统";
                                        putawayOrder.SourceType = 3;
                                        putawayOrder.SiteCode = "";
                                        Context.TPutawayOrders.Add(putawayOrder);
                                        var pallobj = Context.TPallets.FirstOrDefault(x => x.LocationCode == cellCodeNew2);
                                        if (pallobj != null)
                                        {
                                            pallobj.LocationName = toCell.Name;
                                            pallobj.LocationCode = toCell.Code;
                                        }

                                        #endregion
                                        #region 堆垛机                
                                        //堆垛机出库
                                        TaskLiku taskLiku = new TaskLiku()
                                        {
                                            taskId = str,
                                            taskSubType = "103",
                                            startPositionId = inv.LocationCode,
                                            endPositionId = toCell.Code,
                                            palletCode = mater.PallBarcode,
                                            type = 1

                                        };
                                        var taskLikudata = HttpHelper.WCSSendPostRequest("WMS/v1/CMD", taskLiku);
                                        //判断堆垛机返回的状态码不成功的话事务回滚

                                        //成功以后调用wms接口改库存状态

                                        #endregion

                                        //无异常提交事务
                                        msg = "";
                                        tran.Commit();
                                        return true;

                                    }
                                }
                                else if (cellCode.Substring(2, 1) == "4")
                                {
                                    cellCodeNew2 = "B03" + cellCodeNew;
                                    var inventoryList = Context.TInventories.Where(x => x.LocationCode == cellCodeNew2).ToList();
                                    var cellList = Context.TCells.First(x => x.Code == cellCodeNew2);
                                    if (Context.TInventory.FirstOrDefault(x => x.LocationCode == cellCodeNew2) != null)
                                    {


                                        string? cellcode = GetCellCode("2lou", out message);
                                        TCell? toCell = Context.TCells.AsNoTracking().FirstOrDefault(it => it.Code == cellcode);
                                        if (toCell == null)
                                        {
                                            message = "目标仓位不存在";
                                            return false;
                                        }
                                        else
                                        {
                                            toCell.FullStatus = 1;
                                            toCell.IsLock = false;
                                            toCell.BusinessType = 0;
                                            toCell.ModifyDate = DateTime.Now;
                                            toCell.Status = 1;
                                            Context.TCells.Update(toCell);
                                        }

                                        #region 修改库存状态
                                        var tinventorylist = Context.TInventory.Where(it => it.LocationCode == cellCodeNew2);
                                        if (!tinventorylist.Any())
                                        {
                                            message = "库存不存在";
                                            return false;
                                        }
                                        foreach (var inventory in tinventorylist)
                                        {
                                            inventory.LocationId = toCell.Id;
                                            inventory.LocationName = toCell.Name;
                                            inventory.LocationCode = toCell.Code;
                                            inventory.LocationDepth = toCell.DepthIndex;
                                            inventory.LocationLineNo = toCell.LineNo;
                                            inventory.LocationLayerNo = toCell.LayerNo;
                                            inventory.LocationColumnNo = toCell.ColumnNo;
                                            inventory.Status = 2;
                                            inventory.LocationHeightType = toCell.HeightType;
                                            inventory.IsLock = true;
                                            inventory.RoutewayId = toCell.RoutewayId;
                                            Context.Update(inventory);
                                            #region 关联的入库单做处理
                                            var revingobj = Context.TReceivingOrderDetails.Find(inventory.RelatedOrderDetailId);
                                            if (revingobj == null)
                                            {
                                                message = "入库单明细不存在或已被删除";
                                                return false;
                                            }
                                            else
                                            {
                                                revingobj.LocationId = toCell.Id;
                                                revingobj.LocationCode = toCell.Code;
                                                revingobj.LocationName = toCell.Name;
                                                revingobj.ModifyDate = DateTime.Now;
                                                Context.TReceivingOrderDetails.Update(revingobj);
                                            }
                                            //组垛信息
                                            var stackingobj = Context.TStackingStorages.FirstOrDefault(x => x.PalletBarcode == inventory.PalletBarcode && x.BatchNo == revingobj.BatchNo && x.MaterialId == revingobj.MaterialId && x.RelatedOrderDetailId == revingobj.Id);
                                            if (stackingobj == null)
                                            {
                                                message = "组垛信息不存在或已被删除";
                                                return false;
                                            }
                                            else
                                            {
                                                stackingobj.ExpectedLocation = toCell.Code;
                                                if (stackingobj.ActualLocation != null)
                                                {
                                                    stackingobj.ActualLocation = toCell.Code;
                                                }
                                                stackingobj.Status = 0;
                                                Context.TStackingStorages.Update(stackingobj);
                                            }
                                            int stackingid = stackingobj.Id;
                                            #region 指令管理
                                            TInstruct instruct = null;
                                            instruct = new TInstruct
                                            {
                                                WarehouseCode = "A2",
                                                Status = 4,
                                                FromLocation = "",
                                                ToLocation = toCell.Code,
                                                StackingStorageId = stackingobj.Id,
                                                WorkDeviceType = 1,
                                                InstructType = 3,
                                                Action = 0,
                                                RelatedOrderId = revingobj.Id,
                                                DeviceCode = "",
                                                ExpectedToLocation = toCell.Code,
                                                InstructIndex = 1,
                                                PalletBarcode = inventory.PalletBarcode,
                                                ScanedBarcode = inventory.PalletBarcode,
                                                Priority = 9999,
                                                Qty = inventory.AvailableQty == null ? 0 : (decimal)inventory.AvailableQty,
                                                FinishedQty = 0,
                                                StartTime = DateTime.Now,
                                                BusinessGroupId = Guid.NewGuid(),
                                                BusinessType = (int)EmBusinessType.Move,
                                                BillType = (int)revingobj.BillType.GetValueOrDefault(),
                                                LogicalCellAddr = revingobj.Erpcode
                                            };
                                            Context.TInstructs.Add(instruct);
                                            #endregion
                                        }
                                        #endregion


                                        #endregion
                                        #region 上架单
                                        string str = DateTime.Now.ToString("yyyyMMddHHmmss");// + 
                                        TPutawayOrder putawayOrder = new TPutawayOrder();
                                        putawayOrder.Code = str;
                                        putawayOrder.RelatedOrderDetailId = tinventorylist.First().RelatedOrderDetailId;
                                        putawayOrder.StackingStorageId = 0;
                                        putawayOrder.PalletBarcode = tinventorylist.First().PalletBarcode;
                                        putawayOrder.ParentPalletBarcode = tinventorylist.First().ParentPalletBarcode;
                                        putawayOrder.LocationCode = toCell.Code;
                                        putawayOrder.LocationDepth = toCell.DepthIndex == 0 ? null : toCell.DepthIndex;
                                        putawayOrder.Status = 5;
                                        putawayOrder.Qty = tinventorylist.First().AvailableQty;
                                        putawayOrder.CreateDate = DateTime.Now;
                                        putawayOrder.MaterialId = tinventorylist.First().MaterialId;
                                        putawayOrder.MaterialCode = tinventorylist.First().MaterialCode;
                                        putawayOrder.MaterialName = tinventorylist.First().MaterialName;
                                        putawayOrder.MaterialKeyId = tinventorylist.First().MaterialKeyId;
                                        putawayOrder.BatchNo = tinventorylist.First().BatchNo;
                                        putawayOrder.SmallBatchNo = "";
                                        putawayOrder.OwnerId = 0;
                                        putawayOrder.OwnerName = "";
                                        putawayOrder.CreateUserId = 0;
                                        putawayOrder.CreateUserName = "系统";
                                        putawayOrder.SourceType = 3;
                                        putawayOrder.SiteCode = "";
                                        Context.TPutawayOrders.Add(putawayOrder);
                                        var pallobj = Context.TPallets.FirstOrDefault(x => x.LocationCode == cellCodeNew2);
                                        if (pallobj != null)
                                        {
                                            pallobj.LocationName = toCell.Name;
                                            pallobj.LocationCode = toCell.Code;
                                        }

                                        #endregion
                                        #region 堆垛机                
                                        //堆垛机出库
                                        TaskLiku taskLiku = new TaskLiku()
                                        {
                                            taskId = str,
                                            taskSubType = "103",
                                            startPositionId = inv.LocationCode,
                                            endPositionId = toCell.Code,
                                            palletCode = mater.PallBarcode,
                                            type = 1

                                        };
                                        var taskLikudata = HttpHelper.WCSSendPostRequest("WMS/v1/CMD", taskLiku);
                                        //判断堆垛机返回的状态码不成功的话事务回滚

                                        //成功以后调用wms接口改库存状态

                                        #endregion

                                        //无异常提交事务
                                        msg = "";
                                        tran.Commit();
                                        return true;

                                    }
                                }
                            }

                            msg = "";
                            tran.Commit();
                            return true;
                            #endregion

                        }

                    }
                    //无异常提交事务
                    msg = "";
                    tran.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    //事务回滚
                    msg = "catch:" + ex.Message;
                    tran.Rollback();
                    return false;
                }
            }
        }

        private string? GetCellCode(string shCode, out string message)
        {
            message = string.Empty;
            var shelves = Context.TShelves.AsNoTracking().Where(x => x.Status == 1 && x.Code == shCode); // 获取所有货架
            if (shelves == null)
            {
                message = "无可用货架！";
                return null;
            }
            var cellQuery = Context.TCells.AsNoTracking().Where(x => x.Status == 1 && x.ShelfCode == shCode); //获取所有仓位
            if (!cellQuery.Any())
            {
                message = "无可用仓位！";
                return null;
            }

            string? CellCode = "";
            CellCode = cellQuery.Where(r => r.IsMaxDepth == true && r.Status == 1 && r.FullStatus == 0 && r.IsLock == false && r.BusinessType == 0).OrderByDescending(c => c.DepthIndex)
                               .ThenBy(c => c.LayerNo)
                               .ThenBy(c => c.ColumnNo)
                               .ThenBy(c => c.LineNo)
                               .FirstOrDefault()?.Code;
            if (string.IsNullOrEmpty(CellCode))
            {
                CellCode = cellQuery.Where(r => r.IsMaxDepth == false && r.Status == 1 && r.FullStatus == 0 && r.IsLock == false && r.BusinessType == 0).OrderByDescending(c => c.DepthIndex)
                              .ThenBy(c => c.LayerNo)
                              .ThenBy(c => c.ColumnNo)
                              .ThenBy(c => c.LineNo)
                              .FirstOrDefault()?.Code;
                if (string.IsNullOrEmpty(CellCode))
                {
                    message = "当前巷道无可用仓位！";
                    return null;
                }
                return CellCode;
            }
            return CellCode;

        }


        /// <summary>
        /// 分配仓位
        /// </summary>
        /// <param name="srcStation"></param>
        /// <param name="materialId"></param>
        /// <param name="materialKeyId"></param>
        /// <param name="qualityState"></param>
        /// <param name="heightType"></param>
        /// <param name="errorMsg"></param>
        /// <param name="logicalPartCode"></param>
        /// <returns></returns>
        public TCell AllocateCell(/*TStation srcStation*/string orderSn, int materialId, /*int materialKeyId,*/ out string errorMsg, string logicalPartCode = "")
        {
            errorMsg = "";
            if (materialId <= 0)
            {
                return null;
            }
            TCell allotCell = null;
            try
            {
                var shippingList = Context.TShippingOrderDetails.Where(x => x.OrderSn == orderSn);
                if (shippingList.Count() <= 0)
                {
                    return null;
                }
                TDictItem commonlogicalPartType = Context.TDictItems.AsNoTracking().Where(t => t.TypeCode == "LogicPartType" && t.ItemCode == "Common").FirstOrDefault();
                bool hasCell = false;
                int waitIndex = 0;
                string lineOrder = "ASC";
                do
                {
                    var srcStation = Context.TStations.Where(x => x.WhCode == shippingList.First().WarehouseCode).First();

                    var routewayQuery = Context.TRouteways.AsNoTracking().ToList(); //获取所有巷道
                    var cellQuery = Context.TCells.AsNoTracking().ToList(); //获取所以仓位
                    var inventoryQuery = Context.TInventory.AsNoTracking().ToList(); //获取库存数据
                    var shelves = Context.TShelves.AsNoTracking().ToList(); // 获取所有货架
                    var areaQuery = Context.TAreas.AsNoTracking().ToList(); //获取所有库区
                    if (srcStation.WhId > 0) //库房id不等于空的话会根据库房id去筛选
                    {
                        areaQuery = areaQuery.Where(a => a.WhId == srcStation.WhId).ToList(); //获取库房的所有库区
                        routewayQuery = routewayQuery.Where(zw => zw.WhId == srcStation.WhId).ToList();
                        cellQuery = cellQuery.Where(zw => zw.WhId == srcStation.WhId).ToList();
                        inventoryQuery = inventoryQuery.Where(zw => zw.WarehouseId == srcStation.WhId).ToList();
                        shelves = shelves.Where(s => s.WhId == srcStation.WhId).ToList();
                    }
                    List<TRouteway> routewayList = routewayQuery.Where(r => r.Status == 1).ToList();//查询出可以用的巷道
                    var shelvesList = shelves.Where(s => s.Status == 1).ToList(); //查询出可用的货架
                    if (shelvesList == null || shelvesList.Count <= 0)
                    {
                        errorMsg = "无可用货架";
                        return null;
                    }
                    var areasList = areaQuery.Where(a => a.Status == 1).ToList();

                    if (areasList == null || areasList.Count <= 0)
                    {
                        errorMsg = "无可用库区";
                        return null;
                    }

                    if (routewayList != null && routewayList.Count > 0)
                    {
                        List<int> enabledRoutewayIds = routewayList.Select(t => t.Id).ToList();//只取巷道id
                        List<int> enabledShelves = shelvesList.Select(t => t.Id).ToList();//只取货架id
                        List<int> enabledarrea = areasList.Select(t => t.Id).ToList();//只取库区id
                        List<int> routewayIds = cellQuery.Where(t => t.Status == (int)EmCellStatus.Normal && t.BusinessType == 0 && t.IsLock == false && t.FullStatus == 0 && enabledRoutewayIds.Contains((int)t.RoutewayId) && enabledShelves.Contains(t.ShelfId) && enabledarrea.Contains(t.AreaId)).Select(t => t.RoutewayId).Distinct().ToList(); //只取巷道id

                        if (routewayIds == null || routewayIds.Count == 0)
                        {
                            logicalPartCode = commonlogicalPartType == null ? "" : commonlogicalPartType.ItemCode;
                            routewayIds = cellQuery.Where(t => t.Status == (int)EmCellStatus.Normal && t.BusinessType == 0 && t.IsLock == false && t.FullStatus == 0 && enabledRoutewayIds.Contains(t.RoutewayId) && enabledShelves.Contains(t.ShelfId) && enabledarrea.Contains(t.AreaId)).Select(t => t.RoutewayId).Distinct().ToList();
                        }
                        // 从新赋值一下最新的巷道
                        if (routewayIds != null && routewayIds.Count > 0)
                        {
                            routewayList = routewayList.Where(t => routewayIds.Contains(t.Id)).ToList();
                        }
                    }
                    if (routewayList == null || routewayList.Count == 0)
                    {
                        errorMsg = "无可用巷道";
                        return null;
                    }

                    hasCell = true;

                    //只取巷道编号
                    List<string> routewayCodes = routewayList.OrderBy(t => t.DisplayOrder).Select(t => t.Code).ToList();
                    if (lineOrder == "DESC")
                    {
                        routewayCodes = routewayList.OrderByDescending(t => t.DisplayOrder).Select(t => t.Code).ToList();
                    }

                    List<int?> rwIds = routewayList.Select(t => (int?)t.Id).ToList();
                    //找到此巷道同种物料同批次的仓位
                    var depthCellQuery = (from cell in cellQuery
                                          join inv in inventoryQuery
                                          on cell.Id equals inv.LocationId
                                          where rwIds.Contains(cell.RoutewayId)
                                          && inv.MaterialId == materialId
                                          //&& inv.MaterialKeyId == materialKeyId
                                          && cell.Status == (int)EmCellStatus.Normal
                                          && cell.IsLock == false && inv.Status == 1
                                          && cell.BusinessType == 0
                                          select cell
                                         );


                    //var disCell = depthCellQuery.Select(s => new Pcl(s.LineNo, s.LayerNo, s.ColumnNo)).Distinct();
                    //找出同种物料同批次的仓位的 所有同一排同一列同一层的所有深位的仓位
                    //var lineNoList = depthCellQuery.Select(s=>s.LineNo);
                    //var layerNoList = depthCellQuery.Select(s=>s.LayerNo);
                    //var columnNoList = depthCellQuery.Select(s=>s.ColumnNo);
                    //获取同物料同批次的仓位排层列
                    //depthCellQuery = cellQuery.Where(s => disCell.Any(d => d == new Pcl(s.LineNo, s.LayerNo, s.ColumnNo)));
                    depthCellQuery = cellRepository.GetCellByCell(depthCellQuery.ToList()).Distinct();

                    var depthLockCellQuery = (from cell in cellQuery
                                              join inv in inventoryQuery
                                              on cell.Id equals inv.LocationId
                                              where rwIds.Contains(cell.RoutewayId)
                                              && inv.MaterialId == materialId
                                              //&& inv.MaterialKeyId == materialKeyId
                                              && (cell.Status != (int)EmCellStatus.Normal
                                              || cell.IsLock == true || inv.Status != 1)
                                              select cell
                                        );
                    // 根据条件先查询出全部的仓位
                    var celllist = cellQuery.Where(t => t.Status == (int)EmCellStatus.Normal && t.FullStatus == 0 && t.IsLock == false && t.BusinessType == 0 && rwIds.Contains(t.RoutewayId));

                    //筛选出来能用需要使用仓位
                    celllist = celllist.Where(t => depthCellQuery.Where(dc => dc.LayerNo == t.LayerNo && dc.LineNo == t.LineNo && dc.ColumnNo == t.ColumnNo).Any());

                    //把不能用的仓位筛选掉
                    celllist = celllist.Where(t => !depthLockCellQuery.Where(dc => dc.LayerNo == t.LayerNo && dc.LineNo == t.LineNo && dc.ColumnNo == t.ColumnNo).Any()).ToList();
                    //if (!string.IsNullOrEmpty(logicalPartCode))
                    //{
                    //    celllist = celllist.Where(t => t.LogicalPartCode == logicalPartCode).ToList();
                    //}
                    //优先找同种物料、距离最短、深度最深的货位
                    allotCell = celllist.OrderByDescending(c => c.DepthIndex)
                                .ThenBy(c => c.LineNo)
                                .ThenBy(c => c.ColumnNo)
                                .ThenBy(c => c.LayerNo)
                                .FirstOrDefault();


                    if (allotCell == null)//如果没有找到匹配
                    {
                        //寻找一个整深度都是空的仓位
                        var cellsIsMaxDepths = cellQuery.Where(r => r.IsMaxDepth == true && r.Status == 1 && r.FullStatus == 0 && r.IsLock == false && r.BusinessType == 0 && rwIds.Contains(r.RoutewayId)).ToList();

                        if (cellsIsMaxDepths is not null || cellsIsMaxDepths.Count() > 0)
                        {
                            allotCell = cellsIsMaxDepths.OrderByDescending(c => c.DepthIndex)
                                .ThenBy(c => c.LineNo)
                                .ThenBy(c => c.ColumnNo)
                                .ThenBy(c => c.LayerNo)
                                .FirstOrDefault();
                            //OrderBy(c => c.LineNo)
                            //   .ThenBy(c => c.ColumnNo)
                            //   .ThenBy(c => c.LayerNo)
                            //   .ThenByDescending(c => c.DepthIndex)
                            //   .FirstOrDefault();
                            if (allotCell != null)
                            {
                                return allotCell;
                            }
                        }

                        var cellsIsMaxDepthss = cellQuery.Where(r => r.IsMaxDepth == true && r.Status == 1 && r.FullStatus == 0 && r.IsLock == false && r.BusinessType == 0 && rwIds.Contains(r.RoutewayId)).ToList();

                        if (cellsIsMaxDepthss is not null || cellsIsMaxDepthss.Count() > 0)
                        {
                            allotCell = cellsIsMaxDepthss.OrderByDescending(c => c.DepthIndex)
                                .ThenBy(c => c.LineNo)
                                .ThenBy(c => c.ColumnNo)
                                .ThenBy(c => c.LayerNo)
                                .FirstOrDefault();
                            //OrderBy(c => c.LineNo)
                            //   .ThenBy(c => c.ColumnNo)
                            //   .ThenBy(c => c.LayerNo)
                            //   .ThenByDescending(c => c.DepthIndex)
                            //   .FirstOrDefault();
                            if (allotCell != null)
                            {
                                return allotCell;
                            }
                        }
                        int i = 0;
                        int count = routewayList.Count;
                        int? stationSort = srcStation.StationSort;
                        string key = stationSort.GetValueOrDefault() + "_routeway";
                        do
                        {
                            //对巷道进行排序，均分原则
                            string allotCode = GlobalManager.AvgAllot(key, routewayCodes);
                            if (string.IsNullOrEmpty(allotCode))
                            {
                                errorMsg = "无可用巷道";
                                return null;
                            }
                            TRouteway routeway = routewayList.Find(t => t.Code == allotCode);
                            if (routeway == null)
                            {
                                errorMsg = "无可用巷道";
                                return null;
                            }
                            List<int> enabledarea = areasList.Select(t => t.Id).ToList();//只取库区id
                            List<int> enabledShelves = shelvesList.Where(s => s.RoutewayId == routeway.Id && enabledarea.Contains(s.AreaId)).Select(t => t.Id).ToList();//只取货架id
                            if (enabledShelves is null)
                            {
                                errorMsg = "无可用货架";
                                return null;
                            }
                            var cells = cellQuery.Where(t => t.Status == (int)EmCellStatus.Normal && t.FullStatus == 0 && t.IsLock == false && t.BusinessType == 0 && t.RoutewayId == routeway.Id && enabledShelves.Contains(t.ShelfId)).ToList();
                            //if (!string.IsNullOrEmpty(logicalPartCode))
                            //{
                            //    cells = cells.Where(t => t.LogicalPartCode == logicalPartCode).ToList();
                            //}
                            //优先找距离最短、深度最深的货位

                            allotCell = cells.OrderByDescending(c => c.DepthIndex)
                                .ThenBy(c => c.LineNo)
                                .ThenBy(c => c.ColumnNo)
                                .ThenBy(c => c.LayerNo)
                                .FirstOrDefault();
                            #region 注释掉的
                            //if (allotCell != null)
                            //{
                            ////当分配了一个双深位浅位仓位时，需要判断深位是否是同种物料批次，此处是为了校验，正常不会进入该条件。先保留
                            //if (allotCell.DepthIndex == 0 && allotCell.IsMaxDepth == false)
                            //{
                            //    //CellModel depthCell = cellService.GetCell(context, new CellCriteriaModel { IsMaxDepth = true, DepthIndex = 1, LineNO = cellList[0].LineNO, LayerNO = cellList[0].LayerNO, ColumnNO = cellList[0].ColumnNO });
                            //    CellModel depthCell = cellQuery.Where(t => t.IsMaxDepth == true && t.DepthIndex == 1 && t.LineNO == allotCell.LineNO && t.LayerNO == allotCell.LayerNO && t.ColumnNO == allotCell.ColumnNO).FirstOrDefault();
                            //    if (depthCell.Status == EmCellStatus.Normal)
                            //    {
                            //        //深位如果有货
                            //        if (depthCell.FullStatus == 0)
                            //        {
                            //            errorMsg = "仓位分配逻辑有误或数据有误";
                            //            return false;
                            //        }
                            //        InventoryModel inventory = context.Query<InventoryModel>().Where(t => t.LocationId == depthCell.Id).FirstOrDefault();
                            //        if (inventory == null)
                            //        {
                            //            errorMsg = "库存数据有误";
                            //            return false;
                            //        }
                            //        if (inventory.MaterialId != materialId || inventory.MaterialKeyId != materialKeyId||inventory.QualityState!= qualityState)
                            //        {
                            //            errorMsg = "库存数据有误";
                            //            return false;
                            //        }
                            //    }
                            //}
                            //}
                            #endregion
                            if (allotCell != null)
                            {
                                break;
                            }
                            i++;
                        } while (i < count);
                    }
                    if (hasCell && allotCell == null)
                    {
                        int sameMaterialCount = 0;
                        if (rwIds.Count > 0)
                        {
                            if (!string.IsNullOrEmpty(logicalPartCode))
                            {
                                var sameMaterial = (from cell in cellQuery
                                                    join inv in inventoryQuery
                                                    on cell.Id equals inv.LocationId
                                                    where rwIds.Contains(cell.RoutewayId)
                                                    && inv.MaterialId == materialId
                                                    //&& inv.MaterialKeyId == materialKeyId
                                                    && cell.LogicalPartCode == logicalPartCode
                                                    && cellQuery.Where(ct => ct.LayerNo == cell.LayerNo
                                                    && ct.LineNo == cell.LineNo
                                                    && ct.ColumnNo == cell.ColumnNo
                                                    && ct.Status == (int)EmCellStatus.Normal
                                                    && ct.IsLock == false && ct.BusinessType == 0
                                                    && ct.FullStatus == 0).Any()
                                                    && cell.IsLock == false && inv.Status == 1
                                                    && cell.BusinessType == 0
                                                    select cell
                                          ).ToList();
                                sameMaterialCount = sameMaterial.Count();
                            }
                            else
                            {
                                var sameMaterial = (from cell in cellQuery
                                                    join inv in inventoryQuery
                                                    on cell.Id equals inv.LocationId
                                                    where rwIds.Contains(cell.RoutewayId)
                                                    && inv.MaterialId == materialId
                                                    //&& inv.MaterialKeyId == materialKeyId
                                                    && cellQuery.Where(ct => ct.LayerNo == cell.LayerNo
                                                    && ct.LineNo == cell.LineNo
                                                    && ct.ColumnNo == cell.ColumnNo
                                                    && ct.Status == (int)EmCellStatus.Normal
                                                    && ct.IsLock == false && ct.BusinessType == 0
                                                    && ct.FullStatus == 0).Any()
                                                    && cell.IsLock == false && inv.Status == 1
                                                    && cell.BusinessType == 0
                                                    select cell
                                         ).ToList();
                                sameMaterialCount = sameMaterial.Count();
                            }
                        }
                        waitIndex++;
                        if (waitIndex > 20)//最多等待10分钟
                        {
                            break;
                        }
                        hasCell = sameMaterialCount > 0;
                        if (sameMaterialCount > 0)
                        {
                            Thread.Sleep(30000);
                        }
                    }
                    else
                    {
                        if (!hasCell)
                        {
                            errorMsg = "没有仓位可分配";
                        }
                    }
                } while (hasCell && allotCell == null);//没有分配到仓位，同时又有仓位时，则说明深位还未完成，需等待

                return allotCell;
            }
            catch (Exception ex)
            {
                errorMsg = "未知异常:" + ex.Message;
                return null;
            }
        }


        /// <summary>
        /// 添加上架单
        /// </summary>
        /// <param name="putawayOrder"></param>
        /// <returns></returns>
        public List<TPutawayOrder> AddPutawayOrder(out string msg, TShippingOrderDetailPlusDTO model)
        {
            msg = "";
            List<TPutawayOrder> list = new List<TPutawayOrder>();
            List<TPutawayOrderDetail> listDetail = new List<TPutawayOrderDetail>();

            foreach (var item in model.ShippingOrderDetailPlusLockCellDTOs)
            {
                var inventoryList = Context.TInventories.Where(x => x.PalletBarcode == item.PallBarcode);
                if (inventoryList.Count() <= 0)
                {
                    msg = "暂无库存信息";
                    return null;
                }
                TPutawayOrder putawayOrder = new TPutawayOrder();
                putawayOrder.Code = DateTime.Now.ToString("yyyyMMddHHmmss");
                putawayOrder.PalletBarcode = item.PallBarcode;
                putawayOrder.LocationCode = inventoryList.First().LocationCode;
                putawayOrder.Fifodate = DateTime.Now;
                putawayOrder.Status = 4;
                putawayOrder.Qty = item.MaterialNum;
                putawayOrder.CreateDate = DateTime.Now;
                putawayOrder.MaterialId = inventoryList.First().MaterialId;
                putawayOrder.MaterialCode = inventoryList.First().MaterialCode;
                putawayOrder.MaterialName = inventoryList.First().MaterialName;
                putawayOrder.SourceType = 2;
                putawayOrder.ParentPalletBarcode = inventoryList.First().PalletBarcode;
                list.Add(putawayOrder);
                TPutawayOrderDetail putawayOrderDetail = new TPutawayOrderDetail();
                putawayOrderDetail.PutawayOrderId = putawayOrder.Id;
                putawayOrderDetail.PalletBarcode = item.PallBarcode;
                putawayOrderDetail.PackageBarcode = item.PallBarcode;
                putawayOrderDetail.MaterialBarcode = item.MaterialCode;
                listDetail.Add(putawayOrderDetail);
            }
            Context.TPutawayOrders.AddRange(list);
            Context.TPutawayOrderDetails.AddRange(listDetail);


            var IsOk = Context.SaveChanges() > 0;
            if (!IsOk)
            {
                msg = "添加失败";
                return null;
            }
            return list;
        }

        /// <summary>
        /// 添加上架单
        /// </summary>
        /// <param name="putawayOrder"></param>
        /// <returns></returns>
        public List<TPutawayOrder> AddPutawayOrder(out string msg, ProductionRequisitionDto model)
        {
            msg = "";
            List<TPutawayOrder> list = new List<TPutawayOrder>();
            List<TPutawayOrderDetail> listDetail = new List<TPutawayOrderDetail>();

            foreach (var item in model.ChildList)
            {
                var inventoryList = Context.TInventories.Where(x => x.PalletBarcode == item.PallBarcode);
                if (inventoryList.Count() <= 0)
                {
                    msg = "暂无库存信息";
                    return null;
                }
                TPutawayOrder putawayOrder = new TPutawayOrder();
                putawayOrder.Code = DateTime.Now.ToString("yyyyMMddHHmmss");
                putawayOrder.PalletBarcode = item.PallBarcode;
                putawayOrder.LocationCode = inventoryList.First().LocationCode;
                putawayOrder.Fifodate = DateTime.Now;
                putawayOrder.Status = 4;
                putawayOrder.Qty = item.NeedNum;
                putawayOrder.CreateDate = DateTime.Now;
                putawayOrder.MaterialId = inventoryList.First().MaterialId;
                putawayOrder.MaterialCode = inventoryList.First().MaterialCode;
                putawayOrder.MaterialName = inventoryList.First().MaterialName;
                putawayOrder.SourceType = 2;
                putawayOrder.ParentPalletBarcode = inventoryList.First().PalletBarcode;
                list.Add(putawayOrder);
                TPutawayOrderDetail putawayOrderDetail = new TPutawayOrderDetail();
                putawayOrderDetail.PutawayOrderId = putawayOrder.Id;
                putawayOrderDetail.PalletBarcode = item.PallBarcode;
                putawayOrderDetail.PackageBarcode = item.PallBarcode;
                putawayOrderDetail.MaterialBarcode = item.MaterialCode;
                listDetail.Add(putawayOrderDetail);
            }
            Context.TPutawayOrders.AddRange(list);
            Context.TPutawayOrderDetails.AddRange(listDetail);


            var IsOk = Context.SaveChanges() > 0;
            if (!IsOk)
            {
                msg = "添加失败";
                return null;
            }
            return list;
        }



        public List<TPutawayOrder> GetPutawayOrder(out string msg, TShippingOrderDetailPlusDTO model)
        {
            msg = "";
            List<TPutawayOrder> list = new List<TPutawayOrder>();
            foreach (var item in model.ShippingOrderDetailPlusLockCellDTOs)
            {
                var putmodel = Context.TPutawayOrders.Where(x => x.PalletBarcode == item.PallBarcode).OrderByDescending(x => x.CreateDate).ToList();
                if (putmodel.Count <= 0)
                {
                    msg = "暂无相关上架单信息";
                    return null;
                }
                list.Add(putmodel.First());
            }
            return list;

        }

        /// <summary>
        /// 删除出库表
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        //public bool DeleteTShippingOrderDetail(int id)
        public bool DeleteTShippingOrderDetail(string OrderSn, out string errorMsg)
        {
            errorMsg = string.Empty;
            using var tran = Context.Database.BeginTransaction();
            try
            {
                var deleteModel = Context.TShippingOrderDetails.Where(x => x.OrderSn == OrderSn);
                //var delShip = Context.TShippingLockCells.Where(s => s.OrderDetailId == id);
                if (deleteModel == null || deleteModel.Count() <= 0)
                {
                    errorMsg = "找不到要删除的出库单，单号：" + OrderSn;
                    return false;
                }
                if (deleteModel.Any(s => s.Status != 0))
                {
                    errorMsg = "出库单不是创建状态无法删除，单号：" + OrderSn;
                    return false;
                }
                int lockCellId = 0;
                int? inventoryId = 0;
                var updInvList = new List<TInventory>();
                var lockCellList = Context.TShippingLockCells.Where(x => x.OrdeSn == OrderSn).ToList();
                foreach (var lockCell in lockCellList.ToList())
                {
                    lockCellId = lockCell.Id;
                    inventoryId = lockCell.InventoryId;
                    if (inventoryId <= 0)
                    {
                        continue;
                    }
                    // 修改库存状态
                    var invs = Context.TInventories.Find(inventoryId);
                    if (invs != null)
                    {
                        invs.Status = 1;
                        updInvList.Add(invs);
                        Context.TInventory.UpdateRange(updInvList);
                        if (Context.SaveChanges() <= 0)
                        {
                            errorMsg = "删除出库单时,库存信息修改失败,库存ID为:" + invs.Id;
                            tran.Rollback();
                            return false;
                        }
                    }

                    // 删除TShippingLockCells表数据
                    Context.TShippingLockCells.Remove(lockCell);
                    if (Context.SaveChanges() <= 0)
                    {
                        errorMsg = "删除仓位锁定表数据失败,仓位锁定ID为:" + lockCell.Id;
                        tran.Rollback();
                        return false;
                    }

                }
                // 删除TShippingOrderDetails
                Context.TShippingOrderDetails.RemoveRange(deleteModel);
                if (Context.SaveChanges() <= 0)
                {
                    errorMsg = "删除出库单明细表数据失败，出库单号:" + OrderSn;
                    tran.Rollback();
                    return false;
                }
                tran.Commit();
                return true;

            }
            catch (Exception ex)
            {
                errorMsg = "删除出库单catch:" + ex.Message;
                //事务回滚
                tran.Rollback();
                return false;
            }
        }

        // 根据OrderSn查询ID
        private List<int> GetTShippingOrderDetailId(string OrderSn)
        {
            List<int> listInt = new List<int>();

            var list = Context.TShippingOrderDetails.Where(x => x.OrderSn == OrderSn);

            if (list == null)
            {
                return listInt;
            }
            foreach (var item in list)
            {
                listInt.Add(item.Id);
            }
            return listInt;
        }


        /// <summary>
        /// 修改出库单  多物料版本
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool UpdateTshippingOrderDetailPlus(TShippingOrderDetailPlusDTO models, out string errorMsg)
        {
            errorMsg = "修改了出库单";
            using (var tran = Context.Database.BeginTransaction())
            {
                try
                {
                    var updateModelList = Context.TShippingOrderDetails.Where(x => x.OrderSn == models.OrderSn);
                    if (updateModelList == null || updateModelList.Count() <= 0)
                    {
                        tran.Rollback();
                        errorMsg = "要更新的出库单不存在,出库单号：" + models.OrderSn;
                        return false;
                    }
                    //先把出库单中的明细都删除
                    var delOutOrderId = Context.TShippingOrderDetails.Where(s => s.OrderSn == models.OrderSn).Select(s => s.Id);
                    var delLockCell = Context.TShippingLockCells.Where(s => s.OrdeSn == models.OrderSn); //要删除的所有LockCell
                    if (GetStatus(delLockCell.ToList()) != "创建")
                    {
                        tran.Rollback();
                        errorMsg = "出库单不是创建状态";
                        return false;
                    }
                    if (delLockCell == null || delLockCell.Count() <= 0)
                    {
                        tran.Rollback();
                        errorMsg = "仓位锁定表查询失败";
                        return false;
                    }
                    var updInvId = delLockCell.Select(s => s.InventoryId).ToList();
                    var updInvInLockCelll = Context.TInventories.Where(s => updInvId.Contains(s.Id));//要更改状态的库存
                    if (updInvInLockCelll == null || updInvInLockCelll.Count() <= 0)
                    {
                        tran.Rollback();
                        errorMsg = "库存表查询失败";
                        return false;
                    }
                    foreach (var item in updInvInLockCelll)
                    {
                        item.Status = 1;
                    }
                    Context.UpdateRange(updInvInLockCelll);//修改库存
                    if (Context.SaveChanges() <= 0)
                    {
                        tran.Rollback();
                        errorMsg = "库存状态修改失败";
                        return false;
                    }
                    Context.RemoveRange(updateModelList);//删除出库单
                    if (Context.SaveChanges() <= 0)
                    {
                        tran.Rollback();
                        errorMsg = "出库单删除失败";
                        return false;
                    }
                    //Context.RemoveRange(delLockCell);//仓位锁定表 不知道为什么RemoveRange不管用
                    //if (Context.SaveChanges() <= 0)
                    //{
                    //    tran.Rollback();
                    //    errorMsg = "仓位锁定表删除失败";
                    //    return false;
                    //}
                    foreach (var item in delLockCell)
                    {
                        Context.Remove(item);
                        if (Context.SaveChanges() <= 0)
                        {
                            tran.Rollback();
                            errorMsg = "仓位锁定表删除失败";
                            return false;
                        }
                    }
                    //添加出库单明细 仓位锁定表
                    foreach (var item in models.ShippingOrderDetailPlusLockCellDTOs)
                    {
                        //客户
                        var cust = Context.TCustomers.Find(models.CustomerId);
                        if (cust == null)
                        {
                            tran.Rollback();
                            errorMsg = "找不到客户";
                            return false;
                        }
                        //为了查询物料typeCode
                        var material = Context.TMaterials.FirstOrDefault(m => m.Code == item.MaterialCode);
                        if (material == null)
                        {
                            tran.Rollback();
                            errorMsg = "找不到此物料";
                            return false;
                        }

                        //查找库存
                        var invmter = Context.TInventories.Where(s => s.MaterialCode == item.MaterialCode);
                        if (invmter == null || invmter.Count() <= 0)
                        {
                            tran.Rollback();
                            errorMsg = "库存中没有此物料";
                            return false;
                        }
                        //分配出库仓位
                        var lockCellRes = lockCellRepository.LockCell(item.MaterialCode, item.PallBarcode, item.MaterialNum, out var addLockCellList, out var lockerrorMsg);
                        if (!lockCellRes)
                        {
                            tran.Rollback();
                            errorMsg = lockerrorMsg;
                            return false;
                        }
                        TShippingOrderDetail shippingOrderDetail = new TShippingOrderDetail
                        {
                            OrderSn = models.OrderSn, //同一个订单号
                            CustomerId = cust.Id,  // 拿供应商当客户用！
                            CustomerName = cust.Name,
                            CarCord = models.CarCode,
                            MaterialId = item.MaterialId,
                            MaterialName = item.MaterialName,
                            MaterialTypeCode = material.TypeCode,
                            BillType = models.BillType,
                            WarehouseCode = "",
                            WarehouseName = "",
                            AreaCode = "",
                            AreaName = "",
                            BatchNo = "",
                            UnitName = material.UnitName,
                            Qty = item.MaterialNum,
                            Status = 0,
                            StationName = "",
                            CreateDate = DateTime.Now,
                            CreateUserName = "",
                            CreateUserId = 0
                        };

                        //修改托盘满载率
                        var pallList = Context.TPallets.Where(x => x.PalletBarcode == models.ShippingOrderDetailPlusLockCellDTOs.First().PallBarcode);
                        if (pallList.Count() == 0)
                        {
                            tran.Rollback();
                            return false;
                        }
                        var pallListFirst = pallList.First();
                        pallListFirst.LoadFactor = item.LoadFactor;
                        Context.TPallets.Update(pallListFirst);
                        Context.TShippingOrderDetails.Add(shippingOrderDetail);
                        Context.SaveChanges();
                        //货位锁定明细
                        foreach (var addLockCell in addLockCellList)
                        {
                            var inv = Context.TInventories.Where(s => s.Id == addLockCell.InventoryId).FirstOrDefault();
                            if (inv == null)
                                return false;
                            inv.Status = 4;
                            Context.TInventories.Update(inv);
                            //货位锁定明细
                            TShippingLockCell m = new TShippingLockCell
                            {
                                OrdeSn = models.OrderSn,
                                OrderDetailId = shippingOrderDetail.Id,
                                InventoryId = addLockCell.InventoryId,
                                CellId = addLockCell.CellId,
                                CellCode = addLockCell.CellCode,
                                CellName = addLockCell.CellName,
                                PalletBarcode = addLockCell.PalletBarcode,
                                WhId = addLockCell.WhId,
                                CellDepthIndex = 0,
                                StackingStorageId = addLockCell.StackingStorageId,
                                OutQty = item.KeChuCount,
                                InventoryQty = addLockCell.InventoryQty,
                                MaterialId = item.MaterialId,
                                MaterialName = item.MaterialName,
                                MaterialCode = item.MaterialCode,
                                MaterialKeyId = addLockCell.MaterialKeyId,
                                BatchNo = addLockCell.BatchNo,
                                SmallBatchNo = addLockCell.SmallBatchNo,
                                CreateDate = DateTime.Now,
                                RoutewayId = addLockCell.RoutewayId,
                                IsPicking = false,

                            };
                            Context.TShippingLockCells.Add(m);
                            if (Context.SaveChanges() <= 0)
                            {
                                return false;
                            }
                        }
                    }

                    //无异常提交事务
                    tran.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    errorMsg = "cacth:" + ex.Message;
                    return false;
                }
            }
        }


        /// <summary>
        /// 修改出库单 有问题先不用
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool UpdateTshippingOrderDetailPlusNew(TShippingOrderDetailPlusDTO models, out string errorMsg)
        {
            var customerObj = Context.TCustomers.FirstOrDefault(s => s.Id == models.CustomerId);
            if (customerObj == null)
            {
                errorMsg = "要更新的客户不存在";
                return false;
            }

            errorMsg = "修改了出库单";
            using (var tran = Context.Database.BeginTransaction())
            {
                try
                {
                    //出库单
                    var outHouseList = Context.TShippingOrderDetails.Where(x => x.OrderSn == models.OrderSn).ToList();
                    if (outHouseList == null || outHouseList.Count() <= 0)
                    {
                        tran.Rollback();
                        errorMsg = "要更新的出库单不存在,出库单号：" + models.OrderSn;
                        return false;
                    }

                    //出库单明细
                    var dataDetailList = Context.TShippingLockCells
                                                .Where(s => s.OrdeSn == models.OrderSn)
                                                .GroupBy(s => s.OrderDetailId)
                                                .Select(g => new TShippingOrderDetailPlusLockCellDTO(g.First().Id, g.First().MaterialId.GetValueOrDefault(), g.First().MaterialName, g.First().MaterialCode, (int)g.First().OutQty.GetValueOrDefault()))
                                                .ToList();


                    //将数据库中的数据转化为DTO类型 入参
                    var dataInDTO = new TShippingOrderDetailPlusDTO();
                    dataInDTO.OrderSn = outHouseList[0].OrderSn;
                    dataInDTO.CustomerId = outHouseList[0].CustomerId.GetValueOrDefault();
                    dataInDTO.CarCode = outHouseList[0].CarCord;
                    dataInDTO.BillType = outHouseList[0].BillType.GetValueOrDefault();
                    dataInDTO.AreaName = models.AreaName;
                    dataInDTO.Timestamp = models.Timestamp;
                    dataInDTO.ShippingOrderDetailPlusLockCellDTOs = dataDetailList;
                    //出库单无修改
                    if (dataInDTO.OrderSn == models.OrderSn &&
    dataInDTO.CustomerId == models.CustomerId &&
    dataInDTO.CarCode == models.CarCode &&
    dataInDTO.BillType == models.BillType &&
    dataInDTO.AreaName == models.AreaName &&
    dataInDTO.Timestamp == models.Timestamp && dataInDTO.ShippingOrderDetailPlusLockCellDTOs.SequenceEqual(models.ShippingOrderDetailPlusLockCellDTOs))
                    {
                        tran.Rollback();
                        errorMsg = "出库单无修改,出库单号：" + models.OrderSn;
                        return true;
                    }

                    //判断出库单有没有更改
                    if (models.BillType != dataInDTO.BillType || models.CarCode != dataInDTO.CarCode || models.CustomerId != dataInDTO.CustomerId)
                    {
                        foreach (var item in outHouseList)
                        {
                            item.BillType = dataInDTO.BillType;
                            item.CarCord = dataInDTO.CarCode;
                            item.CustomerId = dataInDTO.CustomerId;
                        }
                        Context.UpdateRange(outHouseList);//修改出库单
                        if (Context.SaveChanges() <= 0)
                        {
                            tran.Rollback();
                            errorMsg = "出库单修改失败";
                            return false;
                        }
                    }
                    //判断DTO出库单明细有没有更改
                    foreach (var dto in models.ShippingOrderDetailPlusLockCellDTOs)
                    {
                        //为了查询物料typeCode
                        var material = Context.TMaterials.Find(dto.MaterialId);
                        if (material == null)
                        {
                            tran.Rollback();
                            errorMsg = "找不到此物料";
                            return false;
                        }

                        //如果在入参中明细id=-1,则添加明细,和前段约定好
                        if (dto.TShippingLockCellsId == -1)
                        {
                            var outHouseAdd = new TShippingOrderDetail()
                            {
                                OrderSn = models.OrderSn, //同一个订单号
                                CustomerId = outHouseList[0].Id,  // 拿供应商当客户用！
                                CustomerName = customerObj.Name,
                                CarCord = models.CarCode,
                                MaterialId = material.Id,
                                MaterialName = material.Name,
                                MaterialTypeCode = material.TypeCode,
                                BillType = models.BillType,
                                WarehouseCode = "",
                                WarehouseName = "",
                                AreaCode = "",
                                AreaName = "",
                                BatchNo = "",
                                UnitName = material.UnitName,
                                Qty = dto.MaterialNum,
                                Status = 0,
                                StationName = "",
                                CreateDate = DateTime.Now,
                                CreateUserName = "",
                                CreateUserId = 0
                            };
                            Context.TShippingOrderDetails.Add(outHouseAdd);
                            if (Context.SaveChanges() <= 0)
                            {
                                tran.Rollback();
                                errorMsg = "出库单修改失败";
                                return false;
                            }
                            //分配仓位
                            var lockCellRes = lockCellRepository.LockCell(dto.MaterialCode, dto.PallBarcode, dto.MaterialNum, out var addLockCellList, out var lockerrorMsg);
                            if (!lockCellRes)
                            {
                                tran.Rollback();
                                errorMsg = lockerrorMsg;
                                return false;
                            }
                            foreach (var addLockCell in addLockCellList)
                            {
                                var inv = Context.TInventories.Where(s => s.Id == addLockCell.InventoryId).FirstOrDefault();
                                if (inv == null)
                                    return false;
                                inv.Status = 4;
                                Context.TInventories.Update(inv);
                                var m = new TShippingLockCell
                                {
                                    OrdeSn = models.OrderSn,
                                    OrderDetailId = outHouseAdd.Id,
                                    InventoryId = addLockCell.InventoryId,
                                    CellId = addLockCell.CellId,
                                    CellCode = addLockCell.CellCode,
                                    CellName = addLockCell.CellName,
                                    PalletBarcode = addLockCell.PalletBarcode,
                                    WhId = addLockCell.WhId,
                                    CellDepthIndex = 0,
                                    StackingStorageId = addLockCell.StackingStorageId,
                                    OutQty = addLockCell.OutQty,
                                    InventoryQty = addLockCell.InventoryQty,
                                    MaterialId = dto.MaterialId,
                                    MaterialName = dto.MaterialName,
                                    MaterialCode = dto.MaterialCode,
                                    MaterialKeyId = addLockCell.MaterialKeyId,
                                    BatchNo = addLockCell.BatchNo,
                                    SmallBatchNo = addLockCell.SmallBatchNo,
                                    CreateDate = DateTime.Now,
                                    RoutewayId = addLockCell.RoutewayId,
                                    IsPicking = false
                                };
                                Context.TShippingLockCells.Add(m);
                                Context.SaveChanges();
                            }
                        }
                    }
                    //循环数据库中的出库单明细
                    foreach (var data in dataInDTO.ShippingOrderDetailPlusLockCellDTOs)
                    {
                        //如果没找到入参的id在数据库中对应的数据,就证明是删了
                        var dataDetail = models.ShippingOrderDetailPlusLockCellDTOs.FirstOrDefault(s => s.TShippingLockCellsId == data.TShippingLockCellsId);
                        if (dataDetail == null)
                        {
                            var removeObj = Context.TShippingLockCells.FirstOrDefault(s => s.Id == data.TShippingLockCellsId);
                            if (removeObj == null)
                            {
                                tran.Rollback();
                                errorMsg = "修改失败，找不到出库单明细id:" + data.TShippingLockCellsId;
                                return false;
                            }
                            Context.Remove(removeObj);//删除出库单
                            if (Context.SaveChanges() <= 0)
                            {
                                tran.Rollback();
                                errorMsg = "出库单删除失败";
                                return false;
                            }
                        }
                        //如果找到了判断数量有没有修改
                        else if (dataDetail != null)
                        {

                            //如果入参数量不等于数据库中的数量进行修改 重新给物料分配仓位
                            if (dataDetail.MaterialNum != data.MaterialNum)
                            {
                                var updObj = Context.TShippingLockCells.FirstOrDefault(s => s.Id == data.TShippingLockCellsId);
                                if (updObj == null)
                                {
                                    tran.Rollback();
                                    errorMsg = "修改失败，找不到出库单明细id:" + data.TShippingLockCellsId;
                                    return false;
                                }
                                List<TShippingLockCell> addLockCellList = new List<TShippingLockCell>();
                                var loceCellRes = lockCellRepository.LockCell(updObj.MaterialCode, updObj.PalletBarcode, data.MaterialNum, out addLockCellList, out var lockCellMsg);
                                if (!loceCellRes)
                                {
                                    errorMsg = lockCellMsg;
                                    tran.Rollback();
                                    return false;
                                }

                                //修改分配到的仓位的库存状态
                                var updInvId = addLockCellList.Select(s => s.InventoryId).ToList();
                                var updInvInLockCelll = Context.TInventories.Where(s => updInvId.Contains(s.Id));//要更改状态的库存
                                if (updInvInLockCelll == null || updInvInLockCelll.Count() <= 0)
                                {
                                    tran.Rollback();
                                    errorMsg = "库存表查询失败";
                                    return false;
                                }
                                foreach (var item in updInvInLockCelll)
                                {
                                    item.Status = 1;
                                }
                                Context.UpdateRange(updInvInLockCelll);//修改库存
                                if (Context.SaveChanges() <= 0)
                                {
                                    tran.Rollback();
                                    errorMsg = "库存状态修改失败";
                                    return false;
                                }


                                //货位锁定明细
                                foreach (var addLockCell in addLockCellList)
                                {
                                    //货位锁定明细
                                    TShippingLockCell m = new TShippingLockCell
                                    {
                                        OrdeSn = models.OrderSn,
                                        OrderDetailId = updObj.OrderDetailId,
                                        InventoryId = addLockCell.InventoryId,
                                        CellId = addLockCell.CellId,
                                        CellCode = addLockCell.CellCode,
                                        CellName = addLockCell.CellName,
                                        PalletBarcode = addLockCell.PalletBarcode,
                                        WhId = addLockCell.WhId,
                                        CellDepthIndex = 0,
                                        StackingStorageId = addLockCell.StackingStorageId,
                                        OutQty = addLockCell.OutQty,
                                        InventoryQty = addLockCell.InventoryQty,
                                        MaterialId = updObj.MaterialId,
                                        MaterialName = updObj.MaterialName,
                                        MaterialCode = updObj.MaterialCode,
                                        MaterialKeyId = addLockCell.MaterialKeyId,
                                        BatchNo = addLockCell.BatchNo,
                                        SmallBatchNo = addLockCell.SmallBatchNo,
                                        CreateDate = DateTime.Now,
                                        RoutewayId = addLockCell.RoutewayId,
                                        IsPicking = false
                                    };
                                    Context.TShippingLockCells.Add(m);
                                    if (Context.SaveChanges() <= 0)
                                    {
                                        tran.Rollback();
                                        errorMsg = "库存明细添加失败";
                                        return false;
                                    }
                                }
                            }
                        }
                    }
                    tran.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    errorMsg = "cacth:" + ex.Message;
                    return false;
                }
            }
        }

        /// <summary>
        /// 修改状态
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool UpdTShippingOrderDetailState(ReceivingOrderDetailDto model)
        {
            var robjs = Context.TShippingOrderDetails.Where(s => s.OrderSn == model.OrderSN).ToList();

            if (robjs != null && robjs.Count() != 0)
            {
                foreach (var robj in robjs)
                {
                    switch (model.state)
                    {
                        case 0:
                            var uobj = Context.TUsers.FirstOrDefault(x =>
                                x.Id == model.NowUserId && x.JobNo == model.JobNo);
                            if (uobj != null)
                            {
                                robj.SubmitUserId = model.NowUserId;
                                robj.SubmitUserName = model.NowUserRealName;
                                robj.SubmitDate = DateTime.Now;

                                //修改为：审核通过
                                robj.Status = 2;
                                Context.TShippingOrderDetails.Update(robj);
                                break;
                            }

                            return false;

                        case 1:
                            break;

                        case 2:
                            robj.ModifyUserId = model.NowUserId;
                            robj.ModifyUserName = model.NowUserRealName;
                            robj.ModifyDate = DateTime.Now;
                            //修改为：作业中
                            robj.Status = 3;
                            Context.TShippingOrderDetails.Update(robj);
                            break;

                        case 3:
                            robj.ModifyUserId = model.NowUserId;
                            robj.ModifyUserName = model.NowUserRealName;
                            robj.ModifyDate = DateTime.Now;
                            //修改为：已完成
                            robj.Status = 4;
                            Context.TShippingOrderDetails.Update(robj);
                            break;

                        default:
                            break;
                    }
                }

                return Context.SaveChanges() > 0;
            }

            return false;
        }

        /// <summary>
        /// 一键选定(弃用)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SelectTShippingOrderDetail(TShippingOrderDetail model)
        {
            var OrderDetail = Context.TShippingOrderDetails.FirstOrDefault(m =>
                m.MaterialId == model.MaterialId &&
                m.WarehouseId == model.WarehouseId && m.BatchNo == model.BatchNo && m.Qty == model.Qty);
            if (OrderDetail == null)
            {
                return false; // 找不到对应的出库管理记录，选定失败
            }
            // 设置其他相关字段值，例如物料分类、物料名称、物料批次等

            OrderDetail.MaterialName = model.MaterialName;
            OrderDetail.WarehouseName = model.WarehouseName;
            OrderDetail.BatchNo = model.BatchNo;
            OrderDetail.Qty = model.Qty;
            OrderDetail.MaterialCode = model.MaterialCode;
            OrderDetail.StationId = model.StationId;
            OrderDetail.StationName = model.StationName;
            OrderDetail.OwnerId = model.OwnerId;
            OrderDetail.OwnerName = model.OwnerName;
            OrderDetail.AreaName = model.AreaName;
            OrderDetail.AreaCode = model.AreaCode;
            OrderDetail.ContractNo = model.ContractNo;
            OrderDetail.BillType = model.BillType;
            OrderDetail.DisOrderLineNo = model.DisOrderLineNo;
            OrderDetail.SupplierId = model.SupplierId;
            OrderDetail.SupplierName = model.SupplierName;
            OrderDetail.AuditUserId = model.AuditUserId;
            OrderDetail.AuditUserName = model.AuditUserName;
            OrderDetail.Status = model.Status;
            // 保存修改
            Context.SaveChanges();

            // 创建新的TShippingLockCell实例并赋值
            List<TShippingLockCell> lockCells = new List<TShippingLockCell>();

            //库位
            var Cells = Context.TCells.FirstOrDefault(m => lockCells.Any(x => x.CellId == m.Id));
            //出库详细单
            var orderDetail =
                Context.TShippingOrderDetails.FirstOrDefault(m => lockCells.Any(x => x.OrderDetailId == m.Id));
            //库存
            var inventory = Context.TInventories.FirstOrDefault(m => lockCells.Any(x => x.InventoryId == m.Id));

            if (new TShippingLockCell().InventoryQty >= model.Qty)
            {
                var lockCell = new TShippingLockCell
                {
                    MaterialId = OrderDetail.MaterialId,
                    MaterialCode = model.MaterialCode,
                    MaterialName = model.MaterialName,
                    OrderDetailId = model.Id,
                    OutQty = OrderDetail.Qty,
                    CellName = Cells.Name,
                    WhId = OrderDetail.WarehouseId,
                    InventoryId = inventory.Id,
                    InventoryQty = inventory.AvailableQty,
                    BatchNo = OrderDetail.BatchNo
                };
                lockCells.Add(lockCell);
            }
            else
            {
                // 根据出库数量创建多个TShippingLockCell实例并添加到列表中
                decimal? remainingQty = model.Qty;
                decimal? stockQuantity = inventory.AvailableQty;
                while (remainingQty > 0)
                {
                    var lockCellss = new TShippingLockCell
                    {
                        MaterialId = OrderDetail.MaterialId,
                        MaterialCode = model.MaterialCode,
                        MaterialName = model.MaterialName,
                        OrderDetailId = model.Id,
                        OutQty = OrderDetail.Qty,
                        CellName = Cells.Name,
                        WhId = OrderDetail.WarehouseId,
                        InventoryId = inventory.Id,
                        BatchNo = OrderDetail.BatchNo,
                        InventoryQty = Math.Min(stockQuantity ?? 0, remainingQty ?? 0),
                    };

                    lockCells.Add(lockCellss);

                    remainingQty -= stockQuantity; // 更新剩余数量
                }
            }

            Context.TShippingLockCells.AddRange(lockCells);

            return Context.SaveChanges() > 0;
        }

        /// <summary>
        /// 一键选定（弃用）
        /// </summary>
        /// <param name="qty"></param>
        /// <param name="inventoryId"></param>
        /// <param name="whId"></param>
        /// <param name="materialId"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TShippingLockCell> GetAllTShippingLockCell(TShippingOrderDetail model)
        {
            // 校验物料Id是否为空或无效
            if (model.MaterialId <= 0)
            {
                throw new ArgumentException("请选择物料");
            }

            // 校验数量是否为空或无效
            if (model.Qty <= 0)
            {
                throw new ArgumentException("请选择出库数量");
            }

            if (model.WarehouseId <= 0)
            {
                throw new ArgumentException("请选择仓库");
            }

            if (model.MaterialId <= 0)
            {
                throw new ArgumentException("请选择物料");
            }

            List<TShippingLockCell> selectedCells = new List<TShippingLockCell>();
            // 查询仓位明细表中符合条件的数据
            var query = from cell in Context.TShippingLockCells
                        where cell.InventoryQty >= model.Qty && cell.WhId == model.WarehouseId &&
                              cell.MaterialId == model.MaterialId

                        select cell;

            // 遍历查询结果，并将符合条件的仓位明细添加到返回列表中
            foreach (var cell in query)
            {
                selectedCells.Add(cell);
            }

            return selectedCells;
        }

        /// <summary>
        /// 显示
        /// </summary>
        /// <param name="status"></param>
        /// <param name="houseid"></param>
        /// <param name="name"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TShippingOrderDetail> GetAllTShippingOrderDetail(int? billType, int? houseid, string? name,
            int pageIndex, int pageSize, out int totalCount)
        {
            // 创建查询的基础列表，包含所有的 TShippingOrderDetail 记录
            var query = Context.TShippingOrderDetails.AsQueryable();

            // 根据传入的参数进行筛选
            if (billType.HasValue && billType.Value != 0)
            {
                query = query.Where(m => m.BillType == billType);
            }

            if (houseid.HasValue && houseid.Value != 0)
            {
                query = query.Where(m => m.WarehouseId == houseid);
            }

            if (!string.IsNullOrEmpty(name))
            {
                query = query.Where(m => m.MaterialName == name);
            }

            // 获取符合条件的总记录数
            totalCount = query.Count();

            // 对结果进行排序和分页
            var resultList = query.OrderByDescending(m => m.CreateDate)
                .Skip((pageIndex - 1) * pageSize)
                .Take(pageSize)
                .ToList();

            return resultList;
        }

        /// <summary>
        /// 根据物料Id返回批次号和数量
        /// </summary>
        /// <param name="mid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public BatchNoMaxCount GetMaterialIdById(int materialId, string batchNO = null, int? qualityState = null, string warehouseCode = "", string areaCode = "", int? ownerId = null, int? supplierId = null, string produceFactory = "")
        {
            //数量
            try
            {
                BatchNoMaxCount bc = new BatchNoMaxCount();

                //找出该库存的所有批次号
                var materialKeyQuery = Context.TMaterialKeys;
                var inventoryQuery = Context.TInventories;

                var list = (from mk in materialKeyQuery
                            join inv in inventoryQuery
                            on mk.Id equals inv.MaterialKeyId
                            where mk.MaterialId == materialId
                            select new BatchNoMaxCountDTO(mk.BatchNo, mk.Id)).Distinct().ToList();
                bc.materialKeys = list;

                //仓位状态 货架状态 巷道状态
                var cellQuery = Context.TCells;
                var shelfQuery = Context.TShelves;
                var routewayQuery = Context.TRouteways;
                var TInventoryQuery = (from inv in Context.TInventories
                                       join cell in cellQuery
                                       on inv.LocationCode equals cell.Code
                                       join slf in shelfQuery
                                       on cell.ShelfCode equals slf.Code
                                       join rtw in routewayQuery
                                       on cell.RoutewayId equals rtw.Id
                                       where cell.Status == 1 && slf.Status == 1 && rtw.Status == 1
                                       select inv).ToList();
                //var TInventoryQuery = (from inv in Context.TInventories
                //                       join cell in cellQuery
                //                       on inv.LocationId equals cell.Id
                //                       join slf in shelfQuery
                //                       on cell.ShelfId equals slf.Id
                //                       join rtw in routewayQuery
                //                       on cell.RoutewayId equals rtw.Id
                //                       select inv
                //                      ).ToList();

                var invList = TInventoryQuery.Where(t => t.MaterialId == materialId && t.Status == 1 && t.IsLock == false).ToList();
                if (!string.IsNullOrEmpty(batchNO))
                {
                    invList = invList.Where(t => t.BatchNo == batchNO).ToList();
                }
                if (qualityState != null)
                {
                    invList = invList.Where(t => t.QualityState == qualityState).ToList();
                }
                if (!string.IsNullOrEmpty(warehouseCode))
                {
                    invList = invList.Where(t => t.WarehouseCode == warehouseCode).ToList();
                }
                if (!string.IsNullOrEmpty(areaCode))
                {
                    invList = invList.Where(t => t.AreaCode == areaCode).ToList();
                }
                if (ownerId > 0)
                {
                    invList = invList.Where(t => t.OwnerId == ownerId).ToList();
                }
                if (supplierId > 0)
                {
                    invList = invList.Where(t => t.SupplierId == supplierId).ToList();
                }
                if (!string.IsNullOrEmpty(produceFactory))
                {
                    invList = invList.Where(t => t.ProduceFactory.Contains(produceFactory)).ToList();
                }
                decimal? sum = invList.Sum(t => t.AvailableQty);

                List<int?> status = new List<int?>
                {
                    (int)EmBillStatus.Create,
                    (int)EmBillStatus.Submit,
                    (int)EmBillStatus.Pass,
                };
                //一键出库优先级最高
                var shippingOrderDetailQuery = Context.TShippingOrderDetails.OrderByDescending(t => t.IsOnceOut);
                var slcOdQuery = (from lockCell in Context.TShippingLockCells
                                  join od in shippingOrderDetailQuery
                                  on lockCell.OrderDetailId equals od.Id
                                  select new { lockCell, od }
                                ).ToList();
                var slcOdQueryTest = slcOdQuery.ToList();
                List<TShippingLockCell> lockCells = slcOdQuery.Select(x => x.lockCell).ToList();
                List<TShippingOrderDetail> orderDetails = slcOdQuery.Select(x => x.od).ToList();
                orderDetails = orderDetails.Where(od => od.MaterialId == materialId && status.Contains(od.Status)).ToList();
                lockCells = lockCells.Where(loc => loc.MaterialId == materialId).ToList();
                slcOdQuery = (from lockCell in lockCells
                              join od in orderDetails
                              on lockCell.OrderDetailId equals od.Id
                              select new { lockCell, od }
                        ).ToList();


                //剔除被锁定的库存
                var lockInvIdQuery = (from lockCell in lockCells
                                      join od in orderDetails
                                      on lockCell.OrderDetailId equals od.Id
                                      select lockCell.InventoryId
                            ).Distinct().ToList();
                int lockInvCount = lockInvIdQuery.Count();
                if (lockInvCount > 0)
                {
                    invList = invList.Where(t => !lockInvIdQuery.ToList().Contains(t.Id)).ToList();
                }
                //查出所有匹配的库存
                List<TInventory> TInventoryList = invList.OrderBy(x => x.LocationDepth)
                                                        .ThenBy(x => x.InStockShortDate)
                                                        .ThenByDescending(x => x.AvailableQty)
                                                        .ThenBy(x => x.LocationLineNo)
                                                        .ThenBy(x => x.LocationLayerNo)
                                                        .ThenBy(x => x.LocationColumnNo).ToList();
                //库存可用数量
                decimal totalTInventoryCount = TInventoryList.Sum(t => t.AvailableQty.GetValueOrDefault());
                //当前物料已出库多少

                bc.MaxCount = totalTInventoryCount;
                return bc;

            }
            catch (Exception ex)
            {
                throw ex;
            }

            //BatchNoMaxCount bc = new BatchNoMaxCount();
            ////物料批次
            //var mkobj = Context.TMaterialKeys.FirstOrDefault(x => x.MaterialId == mid);
            ////库存数量
            //var iobj = Context.TInventories.Where(x => x.MaterialId == mid);
            //if (iobj.Count() <= 0)
            //{
            //    return bc;
            //}

            //if (mkobj != null)
            //{
            //    bc.BatchNO.Add(mkobj.BatchNo);
            //}

            //if (iobj != null)
            //{
            //    foreach (var item in iobj.ToList())
            //    {
            //        bc.MaxCount += item.AvailableQty;
            //    }
            //}

            //return bc;
        }

        /// <summary>
        /// 一键选定
        /// </summary>
        /// <param name="materid">物料Id</param>
        /// <param name="count">出库数量</param>
        /// <param name="whid">库房Id</param>
        /// <param name="areaid">库区Id</param>
        /// <param name="supid">供应商Id</param>
        /// <param name="owid">货主Id</param>
        /// <returns></returns>
        public List<TInventory> GetAllTShippingLockCell(int materid, int count, int whid, int areaid, int supid,
            int owid)
        {
            //var shippinglockcell=Context.TShippingLockCells.Where(x=>x.)
            var ilist = Context.TInventories.Where(x => x.MaterialId == materid);
            ilist = ilist.Where(x => x.AvailableQty != 0 && x.Status == 1);
            ilist = ilist.OrderBy(x => x.BatchNo);
            //库房
            if (whid != 0)
            {
                ilist = ilist.Where(x => x.WarehouseId == whid);
            }

            //库区
            if (areaid != 0)
            {
                ilist = ilist.Where(x => x.AreaId == areaid);
            }

            //供应商
            if (supid != 0)
            {
                ilist = ilist.Where(x => x.SupplierId == supid);
            }

            //货主
            if (owid != 0)
            {
                ilist = ilist.Where(x => x.OwnerId == owid);
            }

            List<TInventory> list = new List<TInventory>();
            //收货的数量
            foreach (var item in ilist)
            {
                //decimal? outqty = count - item.AvailableQty;
                if (count == item.AvailableQty)
                {
                    //如果要出库的数量等于该库存的数量则直接返回
                    item.OutQty = item.AvailableQty;
                    list.Add(item);
                    return list;
                }
                else if (count > item.AvailableQty)
                {
                    item.OutQty = item.AvailableQty;
                    list.Add(item);
                    count = Convert.ToInt32(count - item.OutQty);
                }
                else if (count < item.AvailableQty)
                {
                    item.OutQty = count;
                    list.Add(item);
                    return list;
                }
            }

            return list;
        }

        /// <summary>
        /// 获取商品详细
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public List<TShippingGoodsDetail> GetOneTShippingGoodsDetail(int id, int pageIndex, int pageSize, out int totalCount)
        {
            var order = Context.TShippingOrderDetails.Find(id);
            if (order == null)
            {
                totalCount = 0;
                // 订单不存在时返回一个空的列表
                return new List<TShippingGoodsDetail>();
            }
            var details = Context.TShippingGoodsDetails.Where(m => m.OrderDetailId == order.Id).ToList();
            // 获取符合条件的总记录数
            totalCount = details.Count();

            // 对结果进行排序和分页
            var resultList = details.OrderBy(m => m.CreateDate)
                .Skip((pageIndex - 1) * pageSize)
                .Take(pageSize)
                .ToList();
            return resultList;
        }

        public List<TShippingGoodsDetail> GetByNameShippingGoodsDetail(string? name, int pageIndex, int pageSize, out int totalCount)
        {
            var query = Context.TShippingGoodsDetails.AsQueryable();
            if (!string.IsNullOrEmpty(name))
            {
                query = query.Where(m => m.MaterialName == name);
            }
            totalCount = query.Count();

            // 对结果进行排序和分页
            var resultList = query.OrderBy(m => m.CreateDate)
                .Skip((pageIndex - 1) * pageSize)
                .Take(pageSize)
                .ToList();

            return resultList;
        }

        public List<GetChukuDanDTO> GetAllTShippingOrderDetailPlus(DateTime? startTime, DateTime? endTime, int? billType, int? houseid, string? name, int pageIndex, int pageSize, out int totalCount)
        {
            var listNoPage = Context.TShippingOrderDetails.AsEnumerable();
            if (billType != null)
                listNoPage = listNoPage.Where(s => s.BillType == billType);
            if (houseid != null)
                listNoPage = listNoPage.Where(s => s.WarehouseId == houseid);
            if (name != null)
                listNoPage = listNoPage.Where(s => s.MaterialName.Contains(name));
            if (startTime != null && endTime != null)
                listNoPage = listNoPage.Where(s => s.CreateDate.GetValueOrDefault().Date >= startTime && s.CreateDate.GetValueOrDefault().Date <= endTime);
            var items = listNoPage.OrderByDescending(s => s.CreateDate).GroupBy(s => s.OrderSn);
            var list = items.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            totalCount = items.Count();
            List<GetChukuDanDTO> resList = new List<GetChukuDanDTO>();
            foreach (var item in list)
            {
                var key = item.Key;
                var lockCellList = new List<TShippingLockCellGetDTO>();
                var shippoutList = new List<TShippingOrderDetail>();
                foreach (var value in item)
                {
                    var lockCell = Context.TShippingLockCells.Where(s => s.OrderDetailId == value.Id).ToList();
                    foreach (var item1 in lockCell)
                    {
                        var lockCellDTO = new TShippingLockCellGetDTO();
                        lockCellDTO = mapper.Map<TShippingLockCellGetDTO>(item1);
                        lockCellDTO.InvCount = GetInvCount(item1.MaterialCode);
                        lockCellDTO.ProductionTime = ExtractDateFromCode(lockCellDTO.SmallBatchNo);
                        lockCellDTO.keChuCount = lockCellRepository.GetKeChuInvCount(lockCellDTO.MaterialCode);
                        lockCellList.Add(lockCellDTO);
                    }
                    shippoutList.Add(value);
                }
                resList.Add(new GetChukuDanDTO()
                {
                    Status = GetStatus(lockCellList),
                    OrderSn = key,
                    CreateTime = shippoutList[0].CreateDate,
                    Sum = shippoutList.Sum(s => s.Qty),
                    CreateUserName = shippoutList[0].CreateUserName,
                    AuditUserName = shippoutList[0].AuditUserName,
                    shippingOrders = lockCellList,
                    Customer = shippoutList[0].CustomerName,
                    CarCode = shippoutList[0].CarCord
                });
            }
            return resList;
        }
        /// <summary>
        /// 给导出提供数据
        /// </summary>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="billType"></param>
        /// <param name="houseid"></param>
        /// <param name="name"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        public List<TShippingLockCellGetDTO> GetOuHouseToExcel(DateTime? startTime, DateTime? endTime, int? billType, int? houseid, string? name, int pageIndex, int pageSize, out int totalCount)
        {
            var listNoPage = Context.TShippingOrderDetails.AsEnumerable();
            if (billType != null)
                listNoPage = listNoPage.Where(s => s.BillType == billType);
            if (houseid != null)
                listNoPage = listNoPage.Where(s => s.WarehouseId == houseid);
            if (name != null)
                listNoPage = listNoPage.Where(s => s.MaterialName == name);
            if (startTime != null && endTime != null)
                listNoPage = listNoPage.Where(s => s.CreateDate.GetValueOrDefault().Date >= startTime && s.CreateDate.GetValueOrDefault().Date <= endTime);
            var items = listNoPage.OrderByDescending(s => s.CreateDate).GroupBy(s => s.OrderSn);
            var list = items.Skip((pageIndex - 1) * pageSize).Take(pageSize);
            totalCount = items.Count();
            List<TShippingLockCellGetDTO> resList = new List<TShippingLockCellGetDTO>();
            foreach (var item in list)
            {
                var key = item.Key;
                var lockCellList = new List<TShippingLockCellGetDTO>();
                var shippoutList = new List<TShippingOrderDetail>();
                foreach (var value in item)
                {
                    var lockCell = Context.TShippingLockCells.Where(s => s.OrderDetailId == value.Id);
                    foreach (var item1 in lockCell)
                    {
                        var lockCellDTO = new TShippingLockCellGetDTO();
                        lockCellDTO = mapper.Map<TShippingLockCellGetDTO>(item1);
                        lockCellDTO.OrdeSn = key;
                        lockCellDTO.InvCount = GetInvCount(item1.MaterialCode);
                        lockCellDTO.ProductionTime = ExtractDateFromCode(lockCellDTO.SmallBatchNo);
                        lockCellDTO.keChuCount = lockCellRepository.GetKeChuInvCount(lockCellDTO.MaterialCode);
                        lockCellDTO.CarCode = value.CarCord;
                        lockCellDTO.CustomerName = value.CustomerName;
                        lockCellList.Add(lockCellDTO);
                    }
                    shippoutList.Add(value);
                }
                resList.AddRange(lockCellList);
            }
            return resList;
        }
        private string GetStatus(List<TShippingLockCellGetDTO> shippingGoods)
        {
            if (shippingGoods.All(s => s.IsPicking == true))
            {
                return "已完成";
            }
            else if (shippingGoods.All(s => s.IsPicking == false))
            {
                return "创建";
            }
            else
            {
                return "出库中";
            }
        }
        private string GetStatus(List<TShippingLockCell> shippingGoods)
        {
            if (shippingGoods.All(s => s.IsPicking == true))
            {
                return "已完成";
            }
            else if (shippingGoods.All(s => s.IsPicking == false))
            {
                return "创建";
            }
            else
            {
                return "出库中";
            }
        }

        /// <summary>
        /// 根据单号查询明细
        /// </summary>
        /// <param name="orderSn"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TShippingOrderDetail> GetTShippingOrderDetailByOrderSn(string orderSn)
        {
            var list = Context.TShippingOrderDetails
                .Where(x => x.OrderSn == orderSn).ToList();

            return list;
        }

        public UpdGetOutOrder GetOneTShippingOrderDetailPlus(string orderSn)
        {
            var listNoPage = Context.TShippingOrderDetails.AsEnumerable().Where(s => s.OrderSn == orderSn).ToList();
            if (listNoPage.Count() <= 0)
            {
                return null;
            }
            var shippingLockCellList = Context.TShippingLockCells.Where(x => x.OrdeSn == orderSn).ToList();
            var items = listNoPage.OrderByDescending(s => s.CreateDate).GroupBy(s => s.OrderSn);
            UpdGetOutOrder resList = new UpdGetOutOrder();
            List<TShippingOrderDetailPlusLockCellDTO> lockCellDTOs = new List<TShippingOrderDetailPlusLockCellDTO>();

            foreach (var item in shippingLockCellList)
            {
                TShippingOrderDetailPlusLockCellDTO dto = new TShippingOrderDetailPlusLockCellDTO();

                dto.TShippingLockCellsId = item.Id;
                dto.MaterialId = (int)item.MaterialId;
                dto.MaterialName = item.MaterialName;
                dto.MaterialCode = item.MaterialCode;
                var SumCount = Context.TInventories.Where(x => x.MaterialCode == item.MaterialCode).Sum(x => x.AvailableQty);
                dto.MaterialNum = (int)SumCount;
                dto.KeChuCount = item.OutQty;
                dto.PallBarcode = item.PalletBarcode;
                lockCellDTOs.Add(dto);
                resList.shippingOrderDetailPlusLockCellDTOs.Add(dto);
            }
            resList.id = listNoPage.FirstOrDefault().Id;
            resList.OrderSn = listNoPage.FirstOrDefault().OrderSn == null ? "" : listNoPage.FirstOrDefault().OrderSn;
            resList.BillType = (int)listNoPage.FirstOrDefault().BillType == 0 ? 0 : (int)listNoPage.FirstOrDefault().BillType;
            resList.CustomerId = (int)listNoPage.FirstOrDefault()?.CustomerId == 0 ? 0 : (int)listNoPage.FirstOrDefault()?.CustomerId;
            resList.CarCode = listNoPage.FirstOrDefault().CarCord == "" ? "" : listNoPage.FirstOrDefault().CarCord;
            return resList;





            //foreach (var item in items)
            //{
            //    var key = item.Key;
            //    var lockCellList = new List<TShippingLockCell>();
            //    var shippoutList = new List<TShippingOrderDetail>();
            //    foreach (var value in item)
            //    {
            //        var lockCell = Context.TShippingLockCells.Where(s => s.OrderDetailId == value.Id);
            //        foreach (var item1 in lockCell)
            //        {
            //            lockCellList.Add(item1);
            //        }
            //        shippoutList.Add(value);
            //    }

            //    foreach (var lockCell1 in lockCellList)
            //    {
            //        var lockCellobj = new TShippingOrderDetailPlusLockCellDTO
            //        (
            //            lockCell1.Id,
            //            lockCell1.MaterialId.GetValueOrDefault(),
            //            lockCell1.MaterialName,
            //            lockCell1.MaterialCode,
            //            (int)lockCell1.OutQty.GetValueOrDefault()
            //        );
            //        lockCellDTOs.Add(lockCellobj);
            //    }
            //}
            //resList.id = listNoPage[0].Id;
            //resList.OrderSn = listNoPage[0].OrderSn;
            //resList.BillType = listNoPage[0].BillType.GetValueOrDefault();
            //resList.CustomerId = listNoPage[0].CustomerId.GetValueOrDefault();
            //resList.CarCode = listNoPage[0].CarCord;
            //foreach (var item in lockCellDTOs.GroupBy(s => s.MaterialCode))
            //{

            //    foreach (var lockcellitem in shippingLockCellList)
            //    {
            //        var pallBarcodeList = Context.TPallets.Where(x => x.PalletBarcode == lockcellitem.PalletBarcode).ToList();

            //        var lockCellobj = new TShippingOrderDetailPlusLockCellDTO
            //        (
            //            item.First().TShippingLockCellsId,
            //            item.First().MaterialId,
            //            item.First().MaterialName,
            //            item.First().MaterialCode,
            //            item.Sum(s => s.MaterialNum),
            //            lockCellRepository.GetKeChuInvCount(item.First().MaterialCode),
            //            pallBarcodeList.First().PalletBarcode,
            //            pallBarcodeList.First().LoadFactor
            //        );
            //        resList.shippingOrderDetailPlusLockCellDTOs.Add(lockCellobj);
            //    }


            //}
            //resList.shippingOrderDetailPlusLockCellDTOs = resList.shippingOrderDetailPlusLockCellDTOs
            //    .DistinctBy(x => new { x.MaterialCode, x.PallBarcode })
            //    .ToList();

            //return resList;
        }


        private decimal? GetInvCount(string materialCode)
        {
            return Context.TInventories.Where(s => s.MaterialCode == materialCode).ToList().Sum(s => s.AvailableQty);
        }
        /// <summary>
        /// 小批次号拆解
        /// </summary>
        /// <param name="bacNo">小批次号</param>
        /// <returns></returns>
        private int ExtractDateFromCode(string bacNo)
        {
            if (string.IsNullOrEmpty(bacNo))
            {
                return 0;
            }
            if (bacNo.Length < 12)
            {
                return 0;
            }
            string time = bacNo.Substring(2, 8);
            bool containsLetter = time.Any(char.IsLetter);
            if (containsLetter)
            {
                return 0;
            }
            return Convert.ToInt32(time);
        }

        /// <summary>
        /// 出库任务下传
        /// </summary>
        /// <param name="pickDetailsList"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool ShippingTaskDownload(List<PickDetails> pickDetailsList, out string message)
        {
            using (var tran = Context.Database.BeginTransaction())
            {
                try
                {
                    message = "";
                    foreach (var p in pickDetailsList)
                    {
                        #region 许佳杰代码
                        //var shippingOrder = Context.TShippingOrderDetails.FirstOrDefault(x=>x.OrderSn == p.Id);
                        //var pickDetails = pickDetailsList.Where(x => x.Id == p.Id);
                        //var s = new TShippingOrderDetail();
                        //var shippinglock = new TShippingLockCell();
                        //if (shippingOrder!=null || pickDetails.Count() > 1)
                        //{
                        //    //shippingGoods.OrderDetailId = shippingOrder.Id;
                        //    //shippingGoods.OrderDetailNo = p.Id;
                        //    //shippingGoods.StockDetailsId = p.StockDetailsId;
                        //    //shippingGoods.MaterialCode = p.MaterialNo;
                        //    //shippingGoods.MaterialName = p.MaterialDesc;
                        //    //shippingGoods.StockLocation = p.StockLocation;
                        //    //shippingGoods.SupplierNo = p.SupplierNo;
                        //    //shippingGoods.SupplierName = p.SupplierName;
                        //    //shippingGoods.Factory = p.Factory;
                        //    //shippingGoods.FactoryName = p.FactoryName;
                        //    //shippingGoods.BatchNo = p.BatchNo;
                        //    //shippingGoods.PicklistLineNo = p.PicklistLineNo;
                        //    //shippingGoods.StoreMark = p.StoreMark;
                        //    //shippingGoods.Founder = p.Operator;
                        //    //shippingGoods.CreateDate = Convert.ToDateTime(p.CreateDate);
                        //    //shippingGoods.StorageNo = p.StorageNo;
                        //    //shippingGoods.StorageArea = p.StorageArea;
                        //    //shippingGoods.BinNo = p.BinNo;
                        //    //shippingGoods.SerialNumberEnabled = p.SerialNumberEnabled;
                        //    //shippingGoods.QuantityOut = p.QuantityOut;
                        //    //shippingGoods.SerialNo = p.SerialNo;
                        //    //shippingGoods.SupplierNo = p.SupplierNo;
                        //    //shippingGoods.WbsCode = p.WbsCode;
                        //    //shippingGoods.StoreType = p.StoreType;
                        //    //shippingGoods.BaseUnit = p.BaseUnit;
                        //    //Context.TShippingGoodsDetails.Add(shippingGoods);
                        //    //continue;
                        //}
                        #endregion
                        var s = new TShippingOrderDetail();
                        var shippinglock = new TShippingLockCell();
                        //出库单明细
                        s.OrderId = p.Id;
                        s.OrderSn = p.PicklistNo;
                        s.PurOrderLineNo = p.PicklistNo;
                        s.BaseUnit = p.BaseUnit;
                        s.DisOrderNo = p.SalesNo;
                        s.DisOrderLineNo = p.SalesLine;
                        s.SupplierName = p.SupplierName;
                        s.CustomNo = p.CustomNo;
                        s.ProOrderNo = p.Factory;
                        s.WarehouseCode = p.StorageNo;
                        s.ProduceFactory = p.FactoryName;
                        s.CreateUserName = p.Founder;
                        s.SupplierCode = p.SupplierNo;
                        s.CreateDate = Convert.ToDateTime(p.CreateTime);
                        s.Erpcode = p.WbsCode;
                        s.MaterialCode = p.MaterialNo;
                        s.MaterialName = p.MaterialDesc;
                        s.Qty = p.QuantityOut;

                        Context.TShippingOrderDetails.Add(s);
                        Context.SaveChanges();

                        //出库货物单明细                    
                        shippinglock.OrderDetailId = s.Id;
                        shippinglock.StockDetailsId = p.StockDetailsId;
                        shippinglock.OrdeSn = p.PicklistNo;
                        shippinglock.SerialNo = p.SerialNo;
                        shippinglock.SerialNumberEnabled = p.SerialNumberEnabled;
                        shippinglock.MaterialCode = p.MaterialNo;
                        shippinglock.MaterialName = p.MaterialDesc;
                        shippinglock.ParentPalletBarcode = p.StoreMark;
                        //此处暂时有误-下传仓库id为包含字母
                        //shippinglock.WhId = Convert.ToInt32(p.StorageNo);
                        shippinglock.IsPicking = false;
                        shippinglock.StorageArea = p.StorageArea;
                        //托盘条码-必要
                        var inventoryobj = Context.TInventory.AsNoTracking().FirstOrDefault(x => x.MaterialCode == p.MaterialNo && x.MaterialName == p.MaterialDesc && x.BatchNo == p.BatchNo && x.Status == 1 && x.AvailableQty >= p.QuantityOut);
                        if (inventoryobj != null)
                        {
                            shippinglock.PalletBarcode = inventoryobj.PalletBarcode;
                            shippinglock.InventoryId = inventoryobj.Id;
                            shippinglock.CellId = inventoryobj.LocationId;
                            shippinglock.CellDepthIndex = 0;
                            shippinglock.CellCode = inventoryobj.LocationCode;
                            shippinglock.MaterialId = inventoryobj.MaterialId;
                            shippinglock.InventoryQty = inventoryobj.AvailableQty;
                            inventoryobj.Status = 4;
                            Context.TInventory.Update(inventoryobj);
                        }
                        else
                        {
                            message += "未在库存中找到此物料：" + p.MaterialDesc + " 或因库存数量不足！";
                            return false;
                        }
                        //if(inventoryobj.AvailableQty<p.QuantityOut)
                        //{
                        //    message += p.MaterialDesc + "库存数量不足" + p.QuantityOut + "，库存还剩：" + inventoryobj.AvailableQty;
                        //    return false;
                        //}
                        //shippinglock.CellCode = p.BinNo;
                        shippinglock.CellName = p.StockLocation;
                        shippinglock.OutQty = p.QuantityOut;
                        shippinglock.BatchNo = p.BatchNo;
                        shippinglock.StoreType = p.StoreType;
                        Context.TShippingLockCells.Add(shippinglock);
                    }
                    //提交保存
                    Context.SaveChanges();
                    tran.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    message = ex.Message;
                    tran.Rollback();
                    return false;
                    throw;
                }
            }
        }

        /// <summary>
        /// 出库单回传
        /// </summary>
        /// <param name="picks"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<PickDetails> BackShippingOrder()
        {
            List<PickDetails> plist = new List<PickDetails>();
            //出库单
            var sorderlist = Context.TShippingOrderDetails.AsNoTracking().Where(x => x.Status == 4).OrderBy(x => x.CreateDate);
            if (sorderlist.Any())
            {
                foreach (var item in sorderlist)
                {
                    PickDetails pobj = new PickDetails();
                    //出库单明细
                    pobj.Id = item.OrderId;
                    pobj.PicklistNo = item.OrderSn;
                    pobj.PicklistLineNo = item.PurOrderLineNo;
                    pobj.BaseUnit = item.BaseUnit;
                    pobj.SalesNo = item.DisOrderNo;
                    pobj.SalesLine = item.DisOrderLineNo;
                    pobj.SupplierName = item.SupplierName;
                    pobj.CustomNo = item.CustomNo;
                    pobj.Factory = item.ProOrderNo;
                    pobj.FactoryName = item.ProduceFactory;
                    pobj.Founder = item.CreateUserName;
                    pobj.SupplierNo = item.SupplierCode;
                    pobj.CreateTime = Convert.ToString(item.CreateDate);
                    pobj.WbsCode = item.Erpcode;
                    pobj.StorageNo = item.WarehouseCode;

                    //出库单明细
                    var sloclist = Context.TShippingLockCells.AsNoTracking().Where(x => x.OrderDetailId == item.Id);
                    if (sloclist.Any())
                    {
                        foreach (var item2 in sloclist)
                        {

                            //出库货物单明细
                            //立体库库存id-shippinglock.InventoryId = p.StockDetailsId;
                            //shippinglock.OrderDetailId = s.Id;
                            pobj.StockDetailsId = item2.StockDetailsId;
                            pobj.PicklistNo = item2.OrdeSn;
                            pobj.SerialNo = item2.SerialNo;
                            pobj.SerialNumberEnabled = item2.SerialNumberEnabled;
                            pobj.MaterialNo = item2.MaterialCode;
                            pobj.MaterialDesc = item2.MaterialName;
                            pobj.StoreMark = item2.ParentPalletBarcode;
                            pobj.StorageArea = item2.StorageArea;
                            pobj.BinNo = item2.CellCode;
                            pobj.StockLocation = item2.CellName;
                            pobj.QuantityOut = item2.OutQty == null ? 0 : (decimal)item2.OutQty;
                            pobj.BatchNo = item2.BatchNo;
                            pobj.StoreType = item2.StoreType;
                            plist.Add(pobj);
                        }
                    }

                }
                return plist;
            }
            return null;
        }

        /// <summary>
        /// 获取出库物料
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public List<ShippingSelectMaterialDto> GetInventoryByMaterialAll(int pageIndex, int pageSize, string? mname, out int count)
        {
            var list = Context.TInventories.AsQueryable();

            if (mname != null)
            {
                list = list.Where(i => i.MaterialName.Contains(mname));
            }
            //list = list.Skip((pageIndex - 1) * pageSize).Take(pageSize);
            List<ShippingSelectMaterialDto> shippingSelectMaterialDtos = new List<ShippingSelectMaterialDto>();
            foreach (var items in list)
            {

                foreach (var item in list)
                {
                    var pallBarList = Context.TPallets.AsQueryable();
                    if (pallBarList.Count() == 0)
                    {
                        count = 0;
                        return null;
                    }
                    ShippingSelectMaterialDto dto = new ShippingSelectMaterialDto()
                    {
                        Code = item.MaterialCode,
                        Name = item.MaterialName,
                        UnitName = item.UnitName,
                        InvCount = item.AvailableQty,
                        PallBarcode = item.PalletBarcode,

                    };
                    shippingSelectMaterialDtos.Add(dto);
                }
                shippingSelectMaterialDtos = shippingSelectMaterialDtos.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

                count = list.Count();
                return shippingSelectMaterialDtos.ToList();
            }
            count = 0;
            return null;
        }

        /// <summary>
        /// 采购退料
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool AddPurchaseRetreat(PurchaseRetreatDto model, out string msg)
        {
            msg = "添加采购退料单成功";
            using (var tran = Context.Database.BeginTransaction())
            {
                try
                {
                    //判断采购退料单是否重复
                    var orderSnIsHove = Context.TShippingOrderDetails.Where(s => s.OrderSn == model.OrderSn);
                    if (orderSnIsHove != null && orderSnIsHove.Count() > 0)
                    {
                        msg = "采购退料单号已存在,单号为:" + model.OrderSn;
                        return false;
                    }

                    //查询物料是否存在
                    foreach (var item in model.PurchaseRetreatDetailDtos)
                    {
                        var material = Context.TMaterials.FirstOrDefault(m => m.Code == item.TMaterialCode);
                        if (material == null)
                        {
                            msg = $"找不到此物料,物料：{item.TMaterialName},单号：{item.TMaterialCode}";
                            tran.Rollback();
                            return false;
                        }
                        var inventory = Context.TInventories.FirstOrDefault(i => i.MaterialCode == item.TMaterialCode);
                        if (inventory == null)
                        {
                            msg = $"找不到此物料的库存信息,物料：{item.TMaterialName},单号：{item.TMaterialCode}";
                            tran.Rollback();
                            return false;
                        }
                        if (inventory.AvailableQty < item.RetreatNum)
                        {
                            msg = $"物料库存不足,物料：{inventory.MaterialName},单号：{inventory.MaterialCode}";
                            tran.Rollback();
                            return false;
                        }
                    }
                    TWarehouse warehouse = new TWarehouse();

                    if (model.Floor == 1)
                    {
                        warehouse = Context.TWarehouses.Where(x => x.Name == "1楼立体库").FirstOrDefault();

                    }
                    else if (model.Floor == 2)
                    {
                        warehouse = Context.TWarehouses.Where(x => x.Name == "2楼立体库").FirstOrDefault();
                    }
                    else
                    {
                        msg = "楼层输入错误";
                        return false;
                    }
                    TShippingOrderDetail shippingOrderDetail = new TShippingOrderDetail();
                    shippingOrderDetail.OrderSn = barCodeRuleRepository.GetBarCodeSample(2);
                    shippingOrderDetail.Erpcode = model.OrderSn;
                    shippingOrderDetail.PurchaseOrderSn = model.PurchaseOrderSn;
                    shippingOrderDetail.CompanyCode = model.CompanyCode;
                    shippingOrderDetail.CompanyName = model.CompanyName;
                    shippingOrderDetail.WarehouseId = warehouse.Id;
                    shippingOrderDetail.WarehouseCode = warehouse.Code;
                    shippingOrderDetail.WarehouseName = warehouse.Name;
                    Context.TShippingOrderDetails.Add(shippingOrderDetail);
                    List<TShippingGoodsDetail> shippingGoodsDetails = new List<TShippingGoodsDetail>();
                    List<TShippingLockCell> shippingLockCells = new List<TShippingLockCell>();
                    var shippingList = Context.TShippingOrderDetails.FirstOrDefault(x => x.OrderSn == model.OrderSn);
                    foreach (var item in model.PurchaseRetreatDetailDtos)
                    {
                        var inventoryList = Context.TInventories.FirstOrDefault(x => x.MaterialCode == item.TMaterialCode);
                        //TShippingGoodsDetail shippingGoodsDetail = new TShippingGoodsDetail();
                        //var material = Context.TMaterials.FirstOrDefault(m => m.Code == item.TMaterialCode);
                        //shippingGoodsDetail.Iineitem = item.Iineitem;
                        //shippingGoodsDetail.PurchaseIineitem = item.PurchaseIineitem;
                        ////shippingGoodsDetail.OrderDetailId = shippingOrderDetail.Id;
                        //shippingGoodsDetail.MaterialId = material.Id;
                        //shippingGoodsDetail.MaterialCode = material.Code;
                        //shippingGoodsDetail.MaterialName = material.Name;
                        //shippingGoodsDetail.ModelSpec = item.ModelSpec;
                        //shippingGoodsDetail.RetreatNum = item.RetreatNum;
                        //shippingGoodsDetail.RetreatUnitName = item.RetreatUnitName;
                        //shippingGoodsDetail.RetreatUnitCode = item.RetreatUnitCode;
                        //shippingGoodsDetails.Add(shippingGoodsDetail);
                        TShippingLockCell shippingLockCell = new TShippingLockCell();
                        shippingLockCell.OrderDetailId = shippingList.Id;
                        shippingLockCell.OrdeSn = model.OrderSn;
                        shippingLockCell.Iineitem = item.Iineitem;
                        shippingLockCell.PurchaseIineitem = item.PurchaseIineitem;
                        shippingLockCell.TMaterialCode = item.TMaterialCode;
                        shippingLockCell.MaterialCode = item.TMaterialCode;
                        shippingLockCell.TMaterialName = item.TMaterialName;
                        shippingLockCell.MaterialName = item.TMaterialName;
                        shippingLockCell.ModelSpec = item.ModelSpec;
                        shippingLockCell.RetreatNum = item.RetreatNum;
                        shippingLockCell.RetreatUnitName = item.RetreatUnitName;
                        shippingLockCell.RetreatUnitCode = item.RetreatUnitCode;
                        shippingLockCell.OutQty = item.RetreatNum;
                        shippingLockCell.InventoryId = inventoryList.Id;
                        shippingLockCell.CellId = inventoryList.LocationId;
                        shippingLockCell.CellCode = inventoryList.LocationCode;
                        shippingLockCell.CellName = inventoryList.LocationName;
                        shippingLockCell.CellDepthIndex = inventoryList.LocationDepth;
                        shippingLockCell.PalletBarcode = inventoryList.PalletBarcode;
                        shippingLockCell.WhId = inventoryList.WarehouseId;
                        shippingLockCell.OutQty = item.RetreatNum;
                        shippingLockCell.InventoryQty = inventoryList.AvailableQty;
                        shippingLockCell.MaterialId = inventoryList.MaterialId;
                        shippingLockCell.BatchNo = inventoryList.BatchNo;
                        shippingLockCell.MaterialKeyId = inventoryList.MaterialKeyId;
                        shippingLockCell.CreateDate = DateTime.Now;
                        shippingLockCell.OutboundType = 1;
                        shippingLockCells.Add(shippingLockCell);
                    }
                    Context.TShippingLockCells.AddRange(shippingLockCells);
                    if (Context.SaveChanges() <= 0)
                    {
                        msg = "添加采购退料单失败";
                        tran.Rollback();
                        return false;
                    }
                    //无异常提交事务
                    tran.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    //事务回滚
                    msg = "catch:" + ex.Message;
                    tran.Rollback();
                    return false;
                }
            }
        }

        ///// <summary>
        ///// 生产领料
        ///// </summary>
        ///// <param name="model"></param>
        ///// <param name="msg"></param>
        ///// <returns></returns>
        //public bool AddProductionRequisition(ProductionRequisitionDto model, out string msg)
        //{
        //    msg = "添加生产领料单成功";
        //    using (var tran = Context.Database.BeginTransaction())
        //    {
        //        try
        //        {
        //            //判断采购退料单是否重复
        //            var orderSnIsHove = Context.TShippingOrderDetails.Where(s => s.OrderSn == model.OrderSn);
        //            if (orderSnIsHove != null && orderSnIsHove.Count() > 0)
        //            {
        //                msg = "生产领料单号已存在";
        //                return false;
        //            }

        //            //查询物料是否存在
        //            foreach (var item in model.ProductionRequisitionDetailDtos)
        //            {
        //                var material = Context.TMaterials.FirstOrDefault(m => m.Code == item.MaterialCode);
        //                if (material == null)
        //                {
        //                    msg = $"找不到此物料,物料：{item.MaterialName},单号：{item.MaterialCode}";
        //                    tran.Rollback();
        //                    return false;
        //                }
        //                var inventory = Context.TInventories.FirstOrDefault(i => i.MaterialCode == item.MaterialCode);
        //                if (inventory == null)
        //                {
        //                    msg = $"找不到此物料的库存信息,物料：{item.MaterialName},单号：{item.MaterialCode}";
        //                    tran.Rollback();
        //                    return false;
        //                }
        //                if (inventory.AvailableQty < item.NeedNum)
        //                {
        //                    msg = $"物料库存不足,物料：{inventory.MaterialName},单号：{inventory.MaterialCode}";
        //                    tran.Rollback();
        //                    return false;
        //                }
        //            }
        //            TWarehouse warehouse = new TWarehouse();

        //            if (model.Floor == 1)
        //            {
        //                warehouse = Context.TWarehouses.Where(x => x.Name == "1楼立体库").FirstOrDefault();

        //            }
        //            else if (model.Floor == 2)
        //            {
        //                warehouse = Context.TWarehouses.Where(x => x.Name == "2楼立体库").FirstOrDefault();
        //            }
        //            else
        //            {
        //                msg = "楼层输入错误";
        //                return false;
        //            }

        //            TShippingOrderDetail shippingOrderDetail = new TShippingOrderDetail();
        //            shippingOrderDetail.OrderSn = model.OrderSn;
        //            shippingOrderDetail.ProductionOrderSn = model.ProductionOrderSn;
        //            shippingOrderDetail.CompanyCode = model.CompanyCode;
        //            shippingOrderDetail.CompanyName = model.CompanyName;
        //            shippingOrderDetail.ProductName = model.ProductName;
        //            shippingOrderDetail.ProductCode = model.ProductCode;
        //            shippingOrderDetail.WarehouseId = warehouse.Id;
        //            shippingOrderDetail.WarehouseCode = warehouse.Code;
        //            shippingOrderDetail.WarehouseName = warehouse.Name;
        //            shippingOrderDetail.ModelSpec = model.ModelSpec;
        //            shippingOrderDetail.AGVEndPoint = model.Destination;
        //            shippingOrderDetail.ProductionOrderSn = model.WorkOrderSn;

        //            Context.TShippingOrderDetails.Add(shippingOrderDetail);
        //            List<TShippingGoodsDetail> shippingGoodsDetails = new List<TShippingGoodsDetail>();
        //            List<TShippingLockCell> shippingLockCells = new List<TShippingLockCell>();
        //            foreach (var item in model.ProductionRequisitionDetailDtos)
        //            {
        //                //TShippingGoodsDetail shippingGoodsDetail = new TShippingGoodsDetail();
        //                //var material = Context.TMaterials.FirstOrDefault(m => m.Code == item.MaterialCode);
        //                //shippingGoodsDetail.Iineitem = item.Iineitem;
        //                ////shippingGoodsDetail.PurchaseIineitem = item.PurchaseIineitem;
        //                ////shippingGoodsDetail.OrderDetailId = shippingOrderDetail.Id;
        //                //shippingGoodsDetail.MaterialId = material.Id;
        //                //shippingGoodsDetail.MaterialCode = material.Code;
        //                //shippingGoodsDetail.MaterialName = material.Name;
        //                //shippingGoodsDetail.ModelSpec = item.ModelSpec;
        //                //shippingGoodsDetail.NeedNum = item.NeedNum;
        //                //shippingGoodsDetail.UnitName = item.UnitName;
        //                //shippingGoodsDetail.UnitCode = item.UnitCode;
        //                //shippingGoodsDetails.Add(shippingGoodsDetail);
        //                var inventoryList = Context.TInventories.FirstOrDefault(x => x.MaterialCode == item.MaterialCode);
        //                TShippingLockCell shippingLockCell = new TShippingLockCell();
        //                shippingLockCell.OrdeSn = model.OrderSn;
        //                shippingLockCell.Iineitem = item.Iineitem;
        //                shippingLockCell.InventoryId = inventoryList.Id;
        //                shippingLockCell.CellId = inventoryList.LocationId;
        //                shippingLockCell.CellCode = inventoryList.LocationCode;
        //                shippingLockCell.CellName = inventoryList.LocationName;
        //                shippingLockCell.CellDepthIndex = inventoryList.LocationDepth;
        //                shippingLockCell.PalletBarcode = inventoryList.PalletBarcode;
        //                shippingLockCell.WhId = inventoryList.WarehouseId;
        //                shippingLockCell.InventoryQty = inventoryList.AvailableQty;
        //                shippingLockCell.MaterialId = inventoryList.MaterialId;
        //                shippingLockCell.BatchNo = inventoryList.BatchNo;
        //                shippingLockCell.MaterialKeyId = inventoryList.MaterialKeyId;
        //                shippingLockCell.CreateDate = DateTime.Now;
        //                shippingLockCell.OutQty = item.NeedNum;
        //                shippingLockCell.MaterialCode = item.MaterialCode;
        //                shippingLockCell.MaterialName = item.MaterialName;
        //                shippingLockCell.ModelSpec = item.ModelSpec;
        //                shippingLockCell.UnitName = item.UnitName;
        //                shippingLockCell.UnitCode = item.UnitCode;
        //                shippingLockCell.OutboundType = 2;
        //                shippingLockCell.PalletBarcode = item.PallBarcode;
        //                shippingLockCell.BatchNo = item.BatchNo;
        //                shippingLockCell.Weight = item.Weight;
        //                shippingLockCell.WeightUnitName = item.WeightUnitName;
        //                shippingLockCells.Add(shippingLockCell);

        //            }
        //            Context.TShippingLockCells.AddRange(shippingLockCells);
        //            if (Context.SaveChanges() <= 0)
        //            {
        //                msg = "添加生产领料单失败";
        //                tran.Rollback();
        //                return false;
        //            }
        //            //无异常提交事务
        //            tran.Commit();
        //            return true;
        //        }
        //        catch (Exception ex)
        //        {
        //            //事务回滚
        //            msg = "catch:" + ex.Message;
        //            tran.Rollback();
        //            return false;
        //        }
        //    }
        //}


        /// <summary>
        /// 生产领料
        /// </summary>
        /// <param name="model"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public bool AddProductionRequisition(ProductionRequisitionDto model, out string msg)
        {
            msg = "添加出库单成功";
            using (var tran = Context.Database.BeginTransaction())
            {
                try
                {
                    //if (model.OrderSn.Length!=9)
                    //{
                    //    msg = "单号格式有误,必须为9位";
                    //    return false;
                    //}
                    var orderSnIsHove = Context.TShippingOrderDetails.Where(s => s.OrderSn == model.OrderSn);
                    if (orderSnIsHove != null && orderSnIsHove.Count() > 0)
                    {
                        msg = "单号已存在";
                        return false;
                    }
                    //if (string.IsNullOrEmpty(model.CarCode))
                    //{
                    //    msg = "车牌号不能为空";
                    //    return false;
                    //}
                    //var stationObj = Context.TStations.Find(model.StationId);
                    //if (stationObj == null)
                    //{
                    //    msg = "站台查询不到";
                    //    return false;
                    //}
                    //if (stationObj.Status == 0)
                    //{
                    //    msg = "站台已被禁用";
                    //    return false;
                    //}

                    foreach (var mater in model.ChildList)
                    {

                        ////客户
                        //var cust = Context.TCustomers.Find(model.CustomerId);
                        //if (cust == null)
                        //{
                        //    tran.Rollback();
                        //    msg = "找不到客户";
                        //    return false;
                        //}

                        //if (cust.MengNiuStatus == false)
                        //{
                        //    tran.Rollback();
                        //    msg = "客户已被禁用";
                        //    return false;
                        //}

                        //为了查询物料typeCode
                        var material = Context.TMaterials.FirstOrDefault(m => m.Code == mater.MaterialCode);
                        if (material == null)
                        {
                            tran.Rollback();
                            msg = "找不到此物料";
                            return false;
                        }

                        var invmter = Context.TInventories.Where(m => m.MaterialCode == mater.MaterialCode);
                        if (invmter == null || invmter.Count() <= 0)
                        {
                            tran.Rollback();
                            msg = "库存中没有此物料";
                            return false;
                        }

                        var lockCell = lockCellRepository.LockCell(mater.MaterialCode, mater.PallBarcode, mater.NeedNum, out var lockCellList, out var errorMsg);
                        if (!lockCell)
                        {
                            tran.Rollback();
                            msg = errorMsg;
                            return false;
                        }

                        var agvPointList = Context.TAGVBinDingPoint.Where(x => x.TaskType == 1032);
                        if (agvPointList.Count() <= 0)
                        {
                            msg = "此任务类型未配置AGV点位";
                            return false;
                        }

                        var shippingOrderDetail = new TShippingOrderDetail
                        {
                            OrderSn = barCodeRuleRepository.GetBarCodeSample(2),
                            Erpcode = model.OrderSn,
                            ProductionOrderSn = model.ProductionOrderSn,
                            CompanyCode = model.CompanyCode,
                            CompanyName = model.CompanyName,
                            ProductName = model.ProductName,
                            ProductCode = model.ProductCode,
                            ModelSpec = model.ModelSpec,
                            MaterialId = material.Id,
                            MaterialName = mater.MaterialName,
                            MaterialTypeCode = material.TypeCode,
                            BillType = 1032,
                            WarehouseId = invmter.First().WarehouseId,
                            WarehouseCode = invmter.First().WarehouseCode,
                            WarehouseName = invmter.First().WarehouseName,
                            AreaCode = "",
                            AreaName = "",
                            BatchNo = "",
                            UnitName = material.UnitName,
                            Qty = mater.NeedNum,
                            Status = 0,
                            CreateDate = DateTime.Now,
                            StationId = 0,
                            StationName = "测试站台",
                            MaterialCode = mater.MaterialCode,
                            WorkOrderSn = model.WorkOrderSn,
                            AGVStartPoint = agvPointList.FirstOrDefault().AGVStartPoint,
                            AGVEndPoint = model.Destination,
                        };
                        Context.TShippingOrderDetails.Add(shippingOrderDetail);
                        if (Context.SaveChanges() <= 0)
                        {
                            msg = "出库单添加失败,单号：" + model.OrderSn;
                            tran.Rollback();
                            return false;
                        }


                        // 添加货品表
                        //var product = new TShippingGoodsDetail
                        //{
                        //    OrderDetailId = shippingOrderDetail.Id,
                        //    MaterialId = mater.MaterialId,
                        //    MaterialCode = mater.MaterialCode,
                        //    MaterialName = mater.MaterialName,
                        //    Status = 0
                        //};
                        //Context.TShippingGoodsDetails.Add(product);
                        //Context.SaveChanges();

                        //货位锁定明细

                        var shippingDetailList = Context.TShippingOrderDetails.Where(x => x.Erpcode == model.OrderSn).ToList();
                        if (shippingDetailList.Count <= 0)
                        {
                            msg = "出库单未添加到表中";
                            tran.Rollback();
                            return false;
                        }
                        foreach (var item in lockCellList)
                        {
                            int i = 0;
                            var inv = Context.TInventories.Where(s => s.Id == item.InventoryId && s.PalletBarcode == mater.PallBarcode).FirstOrDefault();

                            if (inv == null && i == lockCellList.Count - 1)
                            {
                                msg = "暂无符合条件的库存信息";
                                tran.Rollback();
                                return false;
                            }
                            else if (inv == null)
                            {
                                continue;
                            }

                            inv.Status = 4;
                            Context.TInventories.Update(inv);
                            //货位锁定明细
                            var m = new TShippingLockCell
                            {
                                OrdeSn = shippingDetailList.FirstOrDefault().OrderSn,
                                OrderDetailId = shippingOrderDetail.Id,
                                InventoryId = item.InventoryId,
                                CellId = item.CellId,
                                CellCode = item.CellCode,
                                CellName = item.CellName,
                                PalletBarcode = item.PalletBarcode,
                                WhId = item.WhId,
                                CellDepthIndex = 0,
                                StackingStorageId = item.StackingStorageId,
                                OutQty = mater.NeedNum,
                                InventoryQty = inv.AvailableQty,
                                MaterialId = material.Id,
                                MaterialName = item.MaterialName,
                                MaterialCode = item.MaterialCode,
                                MaterialKeyId = item.MaterialKeyId,
                                BatchNo = item.BatchNo,
                                SmallBatchNo = item.SmallBatchNo,
                                CreateDate = DateTime.Now,
                                RoutewayId = item.RoutewayId,
                                IsPicking = false,
                                Weight = item.Weight,
                                WeightUnitName = item.WeightUnitName,
                                Iineitem = item.Iineitem,
                                ModelSpec = item.ModelSpec,
                                UnitName = item.UnitName,
                                UnitCode = item.UnitCode,

                            };
                            Context.TShippingLockCells.Add(m);
                            if (Context.SaveChanges() <= 0)
                            {
                                msg = "出库单明细添加失败,物料：" + item.MaterialName + ",单号：" + model.OrderSn;
                                tran.Rollback();
                                return false;
                            }
                            i++;
                            #region
                            ////查询双深位的外层是否有货
                            var cellCode = inv.LocationCode;
                            var cellCodeNew = cellCode.Substring(3);
                            string message;
                            var cellCode1 = "";
                            var iscell = "";
                            string cellCodeNew2 = "";

                            if (cellCode.Substring(0, 1) == "A")
                            {
                                if (cellCode.Substring(2, 1) == "3")
                                {
                                    cellCodeNew2 = "A02" + cellCodeNew;
                                    var inventoryList = Context.TInventories.Where(x => x.LocationCode == cellCodeNew2).ToList();
                                    var cellList = Context.TCells.First(x => x.Code == cellCodeNew2);
                                    if (Context.TInventory.FirstOrDefault(x => x.LocationCode == cellCodeNew2) != null)
                                    {

                                        string modifiedcellcode = Regex.Replace(cellCode, "A03", "A02");
                                        string? cellcode = GetCellCode("1lou", out message);
                                        TCell? toCell = Context.TCells.AsNoTracking().FirstOrDefault(it => it.Code == cellcode);
                                        if (toCell == null)
                                        {
                                            message = "目标仓位不存在";
                                            return false;
                                        }
                                        else
                                        {
                                            toCell.FullStatus = 1;
                                            toCell.IsLock = false;
                                            toCell.BusinessType = 0;
                                            toCell.ModifyDate = DateTime.Now;
                                            toCell.Status = 1;
                                            Context.TCells.Update(toCell);
                                        }

                                        #region 修改库存状态
                                        var tinventorylist = Context.TInventory.Where(it => it.LocationCode == modifiedcellcode);
                                        if (!tinventorylist.Any())
                                        {
                                            message = "库存不存在";
                                            return false;
                                        }
                                        foreach (var inventory in tinventorylist)
                                        {
                                            inventory.LocationId = toCell.Id;
                                            inventory.LocationName = toCell.Name;
                                            inventory.LocationCode = toCell.Code;
                                            inventory.LocationDepth = toCell.DepthIndex;
                                            inventory.LocationLineNo = toCell.LineNo;
                                            inventory.LocationLayerNo = toCell.LayerNo;
                                            inventory.LocationColumnNo = toCell.ColumnNo;
                                            inventory.Status = 2;
                                            inventory.LocationHeightType = toCell.HeightType;
                                            inventory.IsLock = true;
                                            inventory.RoutewayId = toCell.RoutewayId;
                                            Context.Update(inventory);
                                            #region 关联的入库单做处理
                                            var revingobj = Context.TReceivingOrderDetails.Find(inventory.RelatedOrderDetailId);
                                            if (revingobj == null)
                                            {
                                                message = "入库单明细不存在或已被删除";
                                                return false;
                                            }
                                            else
                                            {
                                                revingobj.LocationId = toCell.Id;
                                                revingobj.LocationCode = toCell.Code;
                                                revingobj.LocationName = toCell.Name;
                                                revingobj.ModifyDate = DateTime.Now;
                                                Context.TReceivingOrderDetails.Update(revingobj);
                                            }
                                            //组垛信息
                                            var stackingobj = Context.TStackingStorages.FirstOrDefault(x => x.PalletBarcode == inventory.PalletBarcode && x.BatchNo == revingobj.BatchNo && x.MaterialId == revingobj.MaterialId && x.RelatedOrderDetailId == revingobj.Id);
                                            if (stackingobj == null)
                                            {
                                                message = "组垛信息不存在或已被删除";
                                                return false;
                                            }
                                            else
                                            {
                                                stackingobj.ExpectedLocation = toCell.Code;
                                                if (stackingobj.ActualLocation != null)
                                                {
                                                    stackingobj.ActualLocation = toCell.Code;
                                                }
                                                stackingobj.Status = 0;
                                                Context.TStackingStorages.Update(stackingobj);
                                            }
                                            int stackingid = stackingobj.Id;
                                            #region 指令管理
                                            TInstruct instruct = null;
                                            instruct = new TInstruct
                                            {
                                                WarehouseCode = "A2",
                                                Status = 4,
                                                FromLocation = "",
                                                ToLocation = toCell.Code,
                                                StackingStorageId = stackingobj.Id,
                                                WorkDeviceType = 1,
                                                InstructType = 3,
                                                Action = 0,
                                                RelatedOrderId = revingobj.Id,
                                                DeviceCode = "",
                                                ExpectedToLocation = toCell.Code,
                                                InstructIndex = 1,
                                                PalletBarcode = inventory.PalletBarcode,
                                                ScanedBarcode = inventory.PalletBarcode,
                                                Priority = 9999,
                                                Qty = inventory.AvailableQty == null ? 0 : (decimal)inventory.AvailableQty,
                                                FinishedQty = 0,
                                                StartTime = DateTime.Now,
                                                BusinessGroupId = Guid.NewGuid(),
                                                BusinessType = (int)EmBusinessType.Move,
                                                BillType = (int)revingobj.BillType.GetValueOrDefault(),
                                                LogicalCellAddr = revingobj.Erpcode
                                            };
                                            Context.TInstructs.Add(instruct);
                                            #endregion
                                        }
                                        #endregion


                                        #endregion
                                        #region 上架单
                                        string str = DateTime.Now.ToString("yyyyMMddHHmmss");// + 
                                        TPutawayOrder putawayOrder = new TPutawayOrder();
                                        putawayOrder.Code = str;
                                        putawayOrder.RelatedOrderDetailId = tinventorylist.First().RelatedOrderDetailId;
                                        putawayOrder.StackingStorageId = 0;
                                        putawayOrder.PalletBarcode = tinventorylist.First().PalletBarcode;
                                        putawayOrder.ParentPalletBarcode = tinventorylist.First().ParentPalletBarcode;
                                        putawayOrder.LocationCode = toCell.Code;
                                        putawayOrder.LocationDepth = toCell.DepthIndex == 0 ? null : toCell.DepthIndex;
                                        putawayOrder.Status = 5;
                                        putawayOrder.Qty = tinventorylist.First().AvailableQty;
                                        putawayOrder.CreateDate = DateTime.Now;
                                        putawayOrder.MaterialId = tinventorylist.First().MaterialId;
                                        putawayOrder.MaterialCode = tinventorylist.First().MaterialCode;
                                        putawayOrder.MaterialName = tinventorylist.First().MaterialName;
                                        putawayOrder.MaterialKeyId = tinventorylist.First().MaterialKeyId;
                                        putawayOrder.BatchNo = tinventorylist.First().BatchNo;
                                        putawayOrder.SmallBatchNo = "";
                                        putawayOrder.OwnerId = 0;
                                        putawayOrder.OwnerName = "";
                                        putawayOrder.CreateUserId = 0;
                                        putawayOrder.CreateUserName = "系统";
                                        putawayOrder.SourceType = 3;
                                        putawayOrder.SiteCode = "";
                                        Context.TPutawayOrders.Add(putawayOrder);
                                        var pallobj = Context.TPallets.FirstOrDefault(x => x.LocationCode == modifiedcellcode);
                                        if (pallobj != null)
                                        {
                                            pallobj.LocationName = toCell.Name;
                                            pallobj.LocationCode = toCell.Code;
                                        }

                                        #endregion
                                        #region 堆垛机                
                                        //堆垛机出库
                                        TaskLiku taskLiku = new TaskLiku()
                                        {
                                            taskId = str,
                                            taskSubType = "103",
                                            startPositionId = inv.LocationCode,
                                            endPositionId = toCell.Code,
                                            palletCode = mater.PallBarcode,
                                            type = 1

                                        };
                                        var taskLikudata = HttpHelper.WCSSendPostRequest("WMS/v1/CMD", taskLiku);
                                        //判断堆垛机返回的状态码不成功的话事务回滚

                                        //成功以后调用wms接口改库存状态

                                        #endregion

                                        //无异常提交事务
                                        msg = "";
                                        tran.Commit();
                                        return true;
                                    }
                                }

                            }
                            else if (cellCode.Substring(0, 1) == "B")
                            {
                                if (cellCode.Substring(2, 1) == "1")
                                {
                                    cellCodeNew2 = "B02" + cellCodeNew;
                                    var inventoryList = Context.TInventories.Where(x => x.LocationCode == cellCodeNew2).ToList();
                                    var cellList = Context.TCells.First(x => x.Code == cellCodeNew2);
                                    if (Context.TInventory.FirstOrDefault(x => x.LocationCode == cellCodeNew2) != null)
                                    {

                                        string? cellcode = GetCellCode("2lou", out message);
                                        TCell? toCell = Context.TCells.AsNoTracking().FirstOrDefault(it => it.Code == cellcode);
                                        if (toCell == null)
                                        {
                                            message = "目标仓位不存在";
                                            return false;
                                        }
                                        else
                                        {
                                            toCell.FullStatus = 1;
                                            toCell.IsLock = false;
                                            toCell.BusinessType = 0;
                                            toCell.ModifyDate = DateTime.Now;
                                            toCell.Status = 1;
                                            Context.TCells.Update(toCell);
                                        }

                                        #region 修改库存状态
                                        var tinventorylist = Context.TInventory.Where(it => it.LocationCode == cellCodeNew2);
                                        if (!tinventorylist.Any())
                                        {
                                            message = "库存不存在";
                                            return false;
                                        }
                                        foreach (var inventory in tinventorylist)
                                        {
                                            inventory.LocationId = toCell.Id;
                                            inventory.LocationName = toCell.Name;
                                            inventory.LocationCode = toCell.Code;
                                            inventory.LocationDepth = toCell.DepthIndex;
                                            inventory.LocationLineNo = toCell.LineNo;
                                            inventory.LocationLayerNo = toCell.LayerNo;
                                            inventory.LocationColumnNo = toCell.ColumnNo;
                                            inventory.Status = 2;
                                            inventory.LocationHeightType = toCell.HeightType;
                                            inventory.IsLock = true;
                                            inventory.RoutewayId = toCell.RoutewayId;
                                            Context.Update(inventory);
                                            #region 关联的入库单做处理
                                            var revingobj = Context.TReceivingOrderDetails.Find(inventory.RelatedOrderDetailId);
                                            if (revingobj == null)
                                            {
                                                message = "入库单明细不存在或已被删除";
                                                return false;
                                            }
                                            else
                                            {
                                                revingobj.LocationId = toCell.Id;
                                                revingobj.LocationCode = toCell.Code;
                                                revingobj.LocationName = toCell.Name;
                                                revingobj.ModifyDate = DateTime.Now;
                                                Context.TReceivingOrderDetails.Update(revingobj);
                                            }
                                            //组垛信息
                                            var stackingobj = Context.TStackingStorages.FirstOrDefault(x => x.PalletBarcode == inventory.PalletBarcode && x.BatchNo == revingobj.BatchNo && x.MaterialId == revingobj.MaterialId && x.RelatedOrderDetailId == revingobj.Id);
                                            if (stackingobj == null)
                                            {
                                                message = "组垛信息不存在或已被删除";
                                                return false;
                                            }
                                            else
                                            {
                                                stackingobj.ExpectedLocation = toCell.Code;
                                                if (stackingobj.ActualLocation != null)
                                                {
                                                    stackingobj.ActualLocation = toCell.Code;
                                                }
                                                stackingobj.Status = 0;
                                                Context.TStackingStorages.Update(stackingobj);
                                            }
                                            int stackingid = stackingobj.Id;
                                            #region 指令管理
                                            TInstruct instruct = null;
                                            instruct = new TInstruct
                                            {
                                                WarehouseCode = "A01",
                                                Status = 4,
                                                FromLocation = "",
                                                ToLocation = toCell.Code,
                                                StackingStorageId = stackingobj.Id,
                                                WorkDeviceType = 1,
                                                InstructType = 3,
                                                Action = 0,
                                                RelatedOrderId = revingobj.Id,
                                                DeviceCode = "",
                                                ExpectedToLocation = toCell.Code,
                                                InstructIndex = 1,
                                                PalletBarcode = inventory.PalletBarcode,
                                                ScanedBarcode = inventory.PalletBarcode,
                                                Priority = 9999,
                                                Qty = inventory.AvailableQty == null ? 0 : (decimal)inventory.AvailableQty,
                                                FinishedQty = 0,
                                                StartTime = DateTime.Now,
                                                BusinessGroupId = Guid.NewGuid(),
                                                BusinessType = (int)EmBusinessType.Move,
                                                BillType = (int)revingobj.BillType.GetValueOrDefault(),
                                                LogicalCellAddr = revingobj.Erpcode
                                            };
                                            Context.TInstructs.Add(instruct);
                                            #endregion
                                        }
                                        #endregion


                                        #endregion
                                        #region 上架单
                                        string str = DateTime.Now.ToString("yyyyMMddHHmmss");// + 
                                        TPutawayOrder putawayOrder = new TPutawayOrder();
                                        putawayOrder.Code = str;
                                        putawayOrder.RelatedOrderDetailId = tinventorylist.First().RelatedOrderDetailId;
                                        putawayOrder.StackingStorageId = 0;
                                        putawayOrder.PalletBarcode = tinventorylist.First().PalletBarcode;
                                        putawayOrder.ParentPalletBarcode = tinventorylist.First().ParentPalletBarcode;
                                        putawayOrder.LocationCode = toCell.Code;
                                        putawayOrder.LocationDepth = toCell.DepthIndex == 0 ? null : toCell.DepthIndex;
                                        putawayOrder.Status = 5;
                                        putawayOrder.Qty = tinventorylist.First().AvailableQty;
                                        putawayOrder.CreateDate = DateTime.Now;
                                        putawayOrder.MaterialId = tinventorylist.First().MaterialId;
                                        putawayOrder.MaterialCode = tinventorylist.First().MaterialCode;
                                        putawayOrder.MaterialName = tinventorylist.First().MaterialName;
                                        putawayOrder.MaterialKeyId = tinventorylist.First().MaterialKeyId;
                                        putawayOrder.BatchNo = tinventorylist.First().BatchNo;
                                        putawayOrder.SmallBatchNo = "";
                                        putawayOrder.OwnerId = 0;
                                        putawayOrder.OwnerName = "";
                                        putawayOrder.CreateUserId = 0;
                                        putawayOrder.CreateUserName = "系统";
                                        putawayOrder.SourceType = 3;
                                        putawayOrder.SiteCode = "";
                                        Context.TPutawayOrders.Add(putawayOrder);
                                        var pallobj = Context.TPallets.FirstOrDefault(x => x.LocationCode == cellCodeNew2);
                                        if (pallobj != null)
                                        {
                                            pallobj.LocationName = toCell.Name;
                                            pallobj.LocationCode = toCell.Code;
                                        }

                                        #endregion
                                        #region 堆垛机                
                                        //堆垛机出库
                                        TaskLiku taskLiku = new TaskLiku()
                                        {
                                            taskId = str,
                                            taskSubType = "103",
                                            startPositionId = inv.LocationCode,
                                            endPositionId = toCell.Code,
                                            palletCode = mater.PallBarcode,
                                            type = 1

                                        };
                                        var taskLikudata = HttpHelper.WCSSendPostRequest("WMS/v1/CMD", taskLiku);
                                        //判断堆垛机返回的状态码不成功的话事务回滚

                                        //成功以后调用wms接口改库存状态

                                        #endregion

                                        //无异常提交事务
                                        msg = "";
                                        tran.Commit();
                                        return true;

                                    }
                                }
                                else if (cellCode.Substring(2, 1) == "4")
                                {
                                    cellCodeNew2 = "B03" + cellCodeNew;
                                    var inventoryList = Context.TInventories.Where(x => x.LocationCode == cellCodeNew2).ToList();
                                    var cellList = Context.TCells.First(x => x.Code == cellCodeNew2);
                                    if (Context.TInventory.FirstOrDefault(x => x.LocationCode == cellCodeNew2) != null)
                                    {


                                        string? cellcode = GetCellCode("2lou", out message);
                                        TCell? toCell = Context.TCells.AsNoTracking().FirstOrDefault(it => it.Code == cellcode);
                                        if (toCell == null)
                                        {
                                            message = "目标仓位不存在";
                                            return false;
                                        }
                                        else
                                        {
                                            toCell.FullStatus = 1;
                                            toCell.IsLock = false;
                                            toCell.BusinessType = 0;
                                            toCell.ModifyDate = DateTime.Now;
                                            toCell.Status = 1;
                                            Context.TCells.Update(toCell);
                                        }

                                        #region 修改库存状态
                                        var tinventorylist = Context.TInventory.Where(it => it.LocationCode == cellCodeNew2);
                                        if (!tinventorylist.Any())
                                        {
                                            message = "库存不存在";
                                            return false;
                                        }
                                        foreach (var inventory in tinventorylist)
                                        {
                                            inventory.LocationId = toCell.Id;
                                            inventory.LocationName = toCell.Name;
                                            inventory.LocationCode = toCell.Code;
                                            inventory.LocationDepth = toCell.DepthIndex;
                                            inventory.LocationLineNo = toCell.LineNo;
                                            inventory.LocationLayerNo = toCell.LayerNo;
                                            inventory.LocationColumnNo = toCell.ColumnNo;
                                            inventory.Status = 2;
                                            inventory.LocationHeightType = toCell.HeightType;
                                            inventory.IsLock = true;
                                            inventory.RoutewayId = toCell.RoutewayId;
                                            Context.Update(inventory);
                                            #region 关联的入库单做处理
                                            var revingobj = Context.TReceivingOrderDetails.Find(inventory.RelatedOrderDetailId);
                                            if (revingobj == null)
                                            {
                                                message = "入库单明细不存在或已被删除";
                                                return false;
                                            }
                                            else
                                            {
                                                revingobj.LocationId = toCell.Id;
                                                revingobj.LocationCode = toCell.Code;
                                                revingobj.LocationName = toCell.Name;
                                                revingobj.ModifyDate = DateTime.Now;
                                                Context.TReceivingOrderDetails.Update(revingobj);
                                            }
                                            //组垛信息
                                            var stackingobj = Context.TStackingStorages.FirstOrDefault(x => x.PalletBarcode == inventory.PalletBarcode && x.BatchNo == revingobj.BatchNo && x.MaterialId == revingobj.MaterialId && x.RelatedOrderDetailId == revingobj.Id);
                                            if (stackingobj == null)
                                            {
                                                message = "组垛信息不存在或已被删除";
                                                return false;
                                            }
                                            else
                                            {
                                                stackingobj.ExpectedLocation = toCell.Code;
                                                if (stackingobj.ActualLocation != null)
                                                {
                                                    stackingobj.ActualLocation = toCell.Code;
                                                }
                                                stackingobj.Status = 0;
                                                Context.TStackingStorages.Update(stackingobj);
                                            }
                                            int stackingid = stackingobj.Id;
                                            #region 指令管理
                                            TInstruct instruct = null;
                                            instruct = new TInstruct
                                            {
                                                WarehouseCode = "A2",
                                                Status = 4,
                                                FromLocation = "",
                                                ToLocation = toCell.Code,
                                                StackingStorageId = stackingobj.Id,
                                                WorkDeviceType = 1,
                                                InstructType = 3,
                                                Action = 0,
                                                RelatedOrderId = revingobj.Id,
                                                DeviceCode = "",
                                                ExpectedToLocation = toCell.Code,
                                                InstructIndex = 1,
                                                PalletBarcode = inventory.PalletBarcode,
                                                ScanedBarcode = inventory.PalletBarcode,
                                                Priority = 9999,
                                                Qty = inventory.AvailableQty == null ? 0 : (decimal)inventory.AvailableQty,
                                                FinishedQty = 0,
                                                StartTime = DateTime.Now,
                                                BusinessGroupId = Guid.NewGuid(),
                                                BusinessType = (int)EmBusinessType.Move,
                                                BillType = (int)revingobj.BillType.GetValueOrDefault(),
                                                LogicalCellAddr = revingobj.Erpcode
                                            };
                                            Context.TInstructs.Add(instruct);
                                            #endregion
                                        }
                                        #endregion


                                        #endregion
                                        #region 上架单
                                        string str = DateTime.Now.ToString("yyyyMMddHHmmss");// + 
                                        TPutawayOrder putawayOrder = new TPutawayOrder();
                                        putawayOrder.Code = str;
                                        putawayOrder.RelatedOrderDetailId = tinventorylist.First().RelatedOrderDetailId;
                                        putawayOrder.StackingStorageId = 0;
                                        putawayOrder.PalletBarcode = tinventorylist.First().PalletBarcode;
                                        putawayOrder.ParentPalletBarcode = tinventorylist.First().ParentPalletBarcode;
                                        putawayOrder.LocationCode = toCell.Code;
                                        putawayOrder.LocationDepth = toCell.DepthIndex == 0 ? null : toCell.DepthIndex;
                                        putawayOrder.Status = 5;
                                        putawayOrder.Qty = tinventorylist.First().AvailableQty;
                                        putawayOrder.CreateDate = DateTime.Now;
                                        putawayOrder.MaterialId = tinventorylist.First().MaterialId;
                                        putawayOrder.MaterialCode = tinventorylist.First().MaterialCode;
                                        putawayOrder.MaterialName = tinventorylist.First().MaterialName;
                                        putawayOrder.MaterialKeyId = tinventorylist.First().MaterialKeyId;
                                        putawayOrder.BatchNo = tinventorylist.First().BatchNo;
                                        putawayOrder.SmallBatchNo = "";
                                        putawayOrder.OwnerId = 0;
                                        putawayOrder.OwnerName = "";
                                        putawayOrder.CreateUserId = 0;
                                        putawayOrder.CreateUserName = "系统";
                                        putawayOrder.SourceType = 3;
                                        putawayOrder.SiteCode = "";
                                        Context.TPutawayOrders.Add(putawayOrder);
                                        var pallobj = Context.TPallets.FirstOrDefault(x => x.LocationCode == cellCodeNew2);
                                        if (pallobj != null)
                                        {
                                            pallobj.LocationName = toCell.Name;
                                            pallobj.LocationCode = toCell.Code;
                                        }

                                        #endregion
                                        #region 堆垛机                
                                        //堆垛机出库
                                        TaskLiku taskLiku = new TaskLiku()
                                        {
                                            taskId = str,
                                            taskSubType = "103",
                                            startPositionId = inv.LocationCode,
                                            endPositionId = toCell.Code,
                                            palletCode = mater.PallBarcode,
                                            type = 1

                                        };
                                        var taskLikudata = HttpHelper.WCSSendPostRequest("WMS/v1/CMD", taskLiku);
                                        //判断堆垛机返回的状态码不成功的话事务回滚

                                        //成功以后调用wms接口改库存状态

                                        #endregion

                                        //无异常提交事务
                                        msg = "";
                                        tran.Commit();
                                        return true;

                                    }
                                }
                            }

                            msg = "";
                            tran.Commit();
                            return true;
                            #endregion

                        }

                    }
                    //无异常提交事务
                    msg = "";
                    tran.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    //事务回滚
                    msg = "catch:" + ex.Message;
                    tran.Rollback();
                    return false;
                }
            }
        }

        /// <summary>
        /// 销售发货
        /// </summary>
        /// <param name="marketShipmentsDto"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public bool AddMarketShipments(MarketShipmentsDto model, out string msg)
        {
            msg = "添加销售发货单成功";
            using (var tran = Context.Database.BeginTransaction())
            {
                try
                {
                    //判断采购退料单是否重复
                    var orderSnIsHove = Context.TShippingOrderDetails.Where(s => s.OrderSn == model.OrderSn);
                    if (orderSnIsHove != null && orderSnIsHove.Count() > 0)
                    {
                        msg = "销售发货单号已存在";
                        return false;
                    }

                    //查询物料是否存在
                    foreach (var item in model.MarketShipmentsDetailDtos)
                    {
                        var material = Context.TMaterials.FirstOrDefault(m => m.Code == item.MaterialCode);
                        if (material == null)
                        {
                            msg = $"找不到此物料,物料：{item.MaterialName},单号：{item.MaterialCode}";
                            tran.Rollback();
                            return false;
                        }
                        var inventory = Context.TInventories.FirstOrDefault(i => i.MaterialCode == item.MaterialCode);
                        if (inventory == null)
                        {
                            msg = $"找不到此物料的库存信息,物料：{item.MaterialName},单号：{item.MaterialCode}";
                            tran.Rollback();
                            return false;
                        }
                        if (inventory.AvailableQty < item.ShipmentsNum)
                        {
                            msg = $"物料库存不足,物料：{inventory.MaterialName},单号：{inventory.MaterialCode}";
                            tran.Rollback();
                            return false;
                        }
                        if (item.DeliveryTime <= DateTime.Now)
                        {
                            msg = $"收货日期不能小于发货日期";
                            tran.Rollback();
                            return false;
                        }
                    }

                    TWarehouse warehouse = new TWarehouse();

                    if (model.Floor == 1)
                    {
                        warehouse = Context.TWarehouses.Where(x => x.Name == "1楼立体库").FirstOrDefault();

                    }
                    else if (model.Floor == 2)
                    {
                        warehouse = Context.TWarehouses.Where(x => x.Name == "2楼立体库").FirstOrDefault();
                    }
                    else
                    {
                        msg = "楼层输入错误";
                        return false;
                    }

                    TShippingOrderDetail shippingOrderDetail = new TShippingOrderDetail();
                    shippingOrderDetail.OrderSn = barCodeRuleRepository.GetBarCodeSample(2);
                    shippingOrderDetail.Erpcode = model.OrderSn;
                    shippingOrderDetail.CompanyCode = model.CompanyCode;
                    shippingOrderDetail.CompanyName = model.CompanyName;
                    shippingOrderDetail.MarketOrderSn = model.MarketOrderSn;
                    shippingOrderDetail.ShipmentsTime = DateTime.Now;
                    shippingOrderDetail.ClientCode = model.ClientCode;
                    shippingOrderDetail.ClientName = model.ClientName;
                    shippingOrderDetail.WarehouseId = warehouse.Id;
                    shippingOrderDetail.WarehouseCode = warehouse.Code;
                    shippingOrderDetail.WarehouseName = warehouse.Name;
                    Context.TShippingOrderDetails.Add(shippingOrderDetail);
                    List<TShippingGoodsDetail> shippingGoodsDetails = new List<TShippingGoodsDetail>();
                    List<TShippingLockCell> shippingLockCells = new List<TShippingLockCell>();
                    foreach (var item in model.MarketShipmentsDetailDtos)
                    {
                        //TShippingGoodsDetail shippingGoodsDetail = new TShippingGoodsDetail();
                        //var material = Context.TMaterials.FirstOrDefault(m => m.Code == item.MaterialCode);
                        //shippingGoodsDetail.Iineitem = item.Iineitem;
                        //shippingGoodsDetail.MarketOrderSn = item.MarketOrderSn;
                        //shippingGoodsDetail.MarketIineitem = item.MarketIineitem;
                        //shippingGoodsDetail.MaterialId = material.Id;
                        //shippingGoodsDetail.MaterialCode = material.Code;
                        //shippingGoodsDetail.MaterialName = material.Name;
                        //shippingGoodsDetail.ModelSpec = item.ModelSpec;
                        //shippingGoodsDetail.ShipmentsNum = item.ShipmentsNum;
                        //shippingGoodsDetail.UnitName = item.UnitName;
                        //shippingGoodsDetail.UnitCode = item.UnitCode;
                        //shippingGoodsDetail.DeliveryTime = item.DeliveryTime;
                        //shippingGoodsDetails.Add(shippingGoodsDetail);
                        var inventoryList = Context.TInventories.FirstOrDefault(x => x.MaterialCode == item.MaterialCode);
                        var shippingDetailList = Context.TShippingOrderDetails.Where(x => x.Erpcode == model.OrderSn).ToList();
                        if (shippingDetailList.Count <= 0)
                        {
                            msg = "添加出库单信息失败";
                            tran.Rollback();
                            return false;
                        }
                        TShippingLockCell shippingLockCell = new TShippingLockCell();
                        shippingLockCell.OrdeSn = shippingDetailList.FirstOrDefault().OrderSn;
                        shippingLockCell.MarketIineitem = item.MarketIineitem;
                        shippingLockCell.Iineitem = item.Iineitem;
                        shippingLockCell.InventoryId = inventoryList.Id;
                        shippingLockCell.CellId = inventoryList.LocationId;
                        shippingLockCell.CellCode = inventoryList.LocationCode;
                        shippingLockCell.CellName = inventoryList.LocationName;
                        shippingLockCell.CellDepthIndex = inventoryList.LocationDepth;
                        shippingLockCell.PalletBarcode = inventoryList.PalletBarcode;
                        shippingLockCell.WhId = inventoryList.WarehouseId;
                        shippingLockCell.InventoryQty = inventoryList.AvailableQty;
                        shippingLockCell.MaterialId = inventoryList.MaterialId;
                        shippingLockCell.BatchNo = inventoryList.BatchNo;
                        shippingLockCell.MaterialKeyId = inventoryList.MaterialKeyId;
                        shippingLockCell.CreateDate = DateTime.Now;
                        shippingLockCell.OutQty = item.ShipmentsNum;
                        shippingLockCell.MaterialCode = item.MaterialCode;
                        shippingLockCell.MaterialName = item.MaterialName;
                        shippingLockCell.ModelSpec = item.ModelSpec;
                        shippingLockCell.UnitName = item.UnitName;
                        shippingLockCell.UnitCode = item.UnitCode;
                        shippingLockCell.DeliveryTime = item.DeliveryTime;
                        shippingLockCell.OutboundType = 3;
                        shippingLockCells.Add(shippingLockCell);
                    }
                    Context.TShippingGoodsDetails.AddRange(shippingGoodsDetails);
                    if (Context.SaveChanges() <= 0)
                    {
                        msg = "添加销售发货单失败";
                        tran.Rollback();
                        return false;
                    }
                    //无异常提交事务
                    tran.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    //事务回滚
                    msg = "catch:" + ex.Message;
                    tran.Rollback();
                    return false;
                }
            }
        }


        public async Task<bool> PostMESShipping(MESShippingDto dto)
        {
            // 使用 HttpClient 来发送 HTTP 请求
            using (HttpClient client = new HttpClient())
            {
                try
                {

                    //接口地址(待确认)
                    string apiUrl = "127.0.0.1:8080/dts/wmsapi/outbound/insert";
                    string jsonData = JsonConvert.SerializeObject(dto);
                    StringContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");

                    // 发送 POST 请求到指定的 API 地址
                    HttpResponseMessage response = await client.PostAsync(apiUrl, content);

                    if (response.IsSuccessStatusCode)
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Console.WriteLine("Response: " + responseBody);
                        return true;
                    }
                    else
                    {
                        Console.WriteLine("未能调用API。状态代码: " + response.StatusCode);
                        return false;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("出现错误: " + ex.Message);
                    return false;
                }
            }
        }

        /// <summary>
        /// 更新AGV点位
        /// </summary>
        /// <param name="taskType"></param>
        /// <param name="point"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public bool UpAGVPonitMessage(int taskType, string point, out string message)
        {
            message = "";
            var list = Context.TAGVBinDingPoint.FirstOrDefault(x => x.TaskType == taskType);
            if (list == null)
            {
                message = "暂无此业务类型";
                return false;
            }
            list.AGVEndPoint = point;
            Context.TAGVBinDingPoint.Update(list);
            if (Context.SaveChanges() <= 0)
            {
                message = "更新点位失败";
                return false;
            }
            return true;

        }

        /// <summary>
        /// 生产领料出库接口
        /// </summary>
        /// <param name="path"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public MESReturnDto MESinsertBillData(string path, object data)
        {
            MESReturnDto returnDto = new MESReturnDto();

            try
            {
                //string wcsUrl = "http://172.16.1.206:28000/";
                string wcsUrl = "localhost:5047/";
                string url = wcsUrl + path;

                LogHelper.LogInformation("请求参数" + data);

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = "application/json";

                string jsonData = JsonConvert.SerializeObject(data);

                using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
                {
                    writer.Write(jsonData);
                }

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    // 检查响应状态码
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                        {
                            string jsonResponse = reader.ReadToEnd(); // 读取服务器响应的内容
                            returnDto = JsonConvert.DeserializeObject<MESReturnDto>(jsonResponse);
                            if (returnDto.code != "200")
                            {
                                return returnDto;
                            }
                        }
                        returnDto.code = "200";
                        returnDto.msg = "成功";
                        returnDto.status = "200";
                        return returnDto;
                    }
                    else
                    {
                        returnDto.code = response.StatusCode.ToString();
                        returnDto.msg = "HTTP请求失败，状态码：" + response.StatusCode;
                        return returnDto;
                    }
                }
            }
            catch (Exception ex)
            {
                // 处理异常情况
                LogHelper.LogInformation("异常结束" + ex.Message);
                returnDto.code = "500";
                returnDto.msg = "HTTP请求失败，状态码：500";
                return returnDto;
            }
        }


    }
}